angular http请求相关文章
- angular2 http异步请求到数据后,视图中并未更新。可使用ChangeDetectorRef 当changeDetection=ChageDetectionStrategy.OnPush时,需要手动调ChangeDetectorRef.markForCheck()方法,才能将变化更新到视图。
import { Component, OnInit, ChangeDetectionStrategy, ChangeDetectorRef, Injectable } from '@angular/core'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) @Injectable() export class LoginComponent { onResponse(response: any) { this.LoginResult = "login finished"; this.ref.markForCheck(); } }
- angular2 http请求
login.service.ts
login (options: SigninOptions, callback: any) { let body = new HttpParams(); body = body.append('phone', encrypt.encrypt(options.phone)); body = body.append('password', encrypt.encrypt(options.password)); return this.http.post( 'https://www.xxxx.com/login', body.toString().replace(/\+/g, '%2B'), { headers: new HttpHeaders({'Content-Type': 'application/x-www-form-urlencoded', 'Access-Control-Allow-Origin': '*'}) } ).subscribe( (response) => { callback.onResponse(response); }, (error) => { console.log(error);}, () => { console.log('login finished'); } ); }
login.component.ts
onResponse(response: any) { this.LoginResult = "login finished"; this.ref.markForCheck(); }
- 加载子路由 https://blog.csdn.net/xwnxwn/article/details/81908749 需要在子模块的xx.module.ts文件中,import 里加入 CommonModule,才能支持ngFor的使用。记得加入此模块后重启angular,否则可能不生效。