这几天用所学的 Angular4 做小项目实验,实现的是登陆的小功能,中间将有关 http 请求的代码写入到 service 组件,然后将请求所返回的数据通过回调的方法在 component 中进行处理,这步的处理还算简单,只是要注意的是 typeScript 是强类型声明的,如:
post(path: string, data: any, callback?: any)
就因为这个原因卡了我半天的功夫,之前习惯 javaScript 的老写法一时难改。这个还好后面难点是在 service 中的 http 请求中返回数据不一定都是正确,如遇到错误的返回的时候就必须有友好的 alert 组件在窗口的一角来显示这个错误。这就遇到一个问题是 service 如何向 component 传递这一信息。前面所学过的是 componant 组件间的传值。就这个问题在网络上找了很久,找到了一点思路:组件是不会在我修改了servie的值之后就会得到通知,这时候就需要用到 subscribe。于是呼我用以下的方法成功解决了。
import {Injectable} from '@angular/core'; import {Headers, Http} from "@angular/http"; import {Observable} from "rxjs"; import "rxjs/Rx"; import {Subject} from "rxjs/Subject"; @Injectable() export class HttpService { private _url: string; public httpRes: Observable<any>; msgSource = new Subject(); msgObservable = this.msgSource.asObservable(); codeSourde = new Subject(); codeObservable = this.codeSourde.asObservable(); …… post(path: string, data: any, callback?: any) { let uri = this._url + path; let myHeaders: Headers = new Headers(); myHeaders.append('Content-Type', 'application/json'); let parmas = JSON.stringify({ Token: '', Sign: '', Data: JSON.stringify(data) }); this.httpRes = this.http.post(uri, parmas, {headers: myHeaders}).map(res => res.json()); this.httpRes.subscribe( data => { console.log(callback); let res = data; if (!res.IsSuccess) { this.msgSource.next(res.ErrorMsg); this.codeSourde.next(res.ErrorCode); } else { if (callback != undefined) { callback(res.Data); } } } ); } }
然后在 alertComponent 中输入订阅代码来接收 httpService 传来的消息,然后通过“ngDoCheck”钩子来检测属性值的变化,从而做出相应的动作变化 :
import {Component, DoCheck, Input, OnInit} from '@angular/core'; import {HttpService} from "../service/http.service"; import {mySetInterval} from "../public/common"; @Component({ selector: 'app-alert', templateUrl: './alert.component.html', styleUrls: ['./alert.component.css'] }) export class AlertComponent implements OnInit, DoCheck { alertCode: number; alertMsg: string; alertClass: string; alertHidden: boolean; constructor(private httpServ: HttpService) { httpServ.msgObservable.subscribe(msg => this.alertMsg = msg); httpServ.codeObservable.subscribe(code => this.alertCode = code); } ngOnInit() { this.alertHidden = true; } ngDoCheck(): void { if (this.alertMsg != null && this.alertCode != null) { this.alertHidden = false; …… } } }