在 app.module.ts 中引入 HttpClientModule 並注入
import {HttpClientModule} from '@angular/common/http';
imports: [ BrowserModule, HttpClientModule ]
在用到的地方引入 HttpClient 並在構造函數聲明
import {HttpClient} from "@angular/common/http";
構造函數聲明
constructor(public http:HttpClient) { }
雙向數據綁定:
public username="";
publci password="";
在表單中添加綁定:
[(ngModel)]="username"
[(ngModel)]="password"
登錄函數
doLogin(){ const httpOptions={ headers:new HttpHeaders({ 'Content-Type':'application/json' }) }; var api='http://192.168.31.42:8087/user/login'; this.http.post(api,{ username:this.username, password:this.password },httpOptions).subscribe(respone=>{ console.log(respone); }); }
登錄成功 后路由跳轉:
this.router.navigate(['/homepage']);
2,路由跳轉
找到 app-routing.module.ts 配置路由
// 配置路由 const routes: Routes = [ {path: 'home', component: HomeComponent}, {path: 'news', component: NewsComponent}, {path: 'newscontent/:id', component: NewscontentComponent}, { path: '', redirectTo: '/home', pathMatch: 'full' } ];
routerLink 跳轉頁面
<a [routerLink]="['/homepage']" routerLinkActive="active">首頁</a>
<a [routerLink]="['/cards']" routerLinkActive="active">填單</a>
路由帶參傳遞
<a routerLink="/detail/{{item.id}}"></a>
在聲明路由配置中:
<a routerLink="/detail/{{item.id}}">