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://www.cnblogs.com/sunada2005/p/12328064.html