1. app/app.module.ts, 引入HttpClientModule
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { RouterModule, Routes } from '@angular/router'; import { AppComponent } from './app.component'; import { LoginComponent } from './login/login.component'; import { AdminusersComponent } from './adminusers/adminusers.component'; import { AdmintrainersComponent } from './admintrainers/admintrainers.component'; @NgModule({ declarations: [ AppComponent, LoginComponent, AdminusersComponent, AdmintrainersComponent ], imports: [ BrowserModule, ReactiveFormsModule, HttpClientModule, RouterModule.forRoot([ { path: 'userlogin', component: LoginComponent }, { path: 'userlist', component: AdminusersComponent }, { path: 'trainerlist', component: AdmintrainersComponent } ]) ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } |
2. login.component.ts中使用httpclient
import { Component, OnInit } from '@angular/core'; import { HttpClient, HttpHeaders,HttpParams } from '@angular/common/http'; import { map } from 'rxjs/operators'; import { Router} from '@angular/router'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { myRawToken="haven't got"; constructor(private http: HttpClient, private router: Router) { } ngOnInit() { } login(username: string, pass: string) { const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json;charset=UTF-8', 'Authorization': 'my-auth-token', 'responseType': 'text' }), params: new HttpParams().append('username', username).append('password', pass) }; this.http.post<any>('http://127.0.0.1:8080/auth/login',"", httpOptions) .subscribe( (val) => { alert(JSON.stringify(val)+" tokena= "+val.token); console.log("POST call successful value returned in body", val); }, response => {alert("response:"+response.status+":message="+response.message+response.data); console.log("POST call in error", response); }, ); this.router.navigateByUrl("userlist"); } } |