Angular2的Promise和Observable訪問介面模式

邊邊上的草原發表於2017-11-29

此兩者區別,不在贅述:詳情見
blog.csdn.net/u010130282/…

下面將專案中運用的方式分享給大家:

1.promise的訪問模式

檔案:auth.service.ts
 //需要匯入的檔案
 import "rxjs/add/operator/toPromise";
 /**
 * post請求
 * @param url 請求地址
 * @param body 請求引數
 */
authPost(url: string, body: any): Promise<RequestResult> {
    let headers = this.initAuthHeaders();
    this.spinService.spin(true);
    return this.http.post(
        url,
        AuthService.buildURLSearchParams(body),
        { headers: headers }
    ).toPromise()
        .then(response => {
            let result = response.json() as RequestResult;
            this.spinService.spin(false);
            return result;
        }
        )
        .catch(this.handleError);
}

檔案:xx.service.ts
/**
 * 連鎖管理:查詢總數
 * @param param 
 */
countChain(param: any): Promise<RequestResult> {
    let URL = environment.appmPlusApi + "chain/getChainListCount";
    return this.service.authPost(URL, param).then(result => { return result; })
}

檔案:xx.component.ts
//查詢總數
searchCount() {
    this.chainService.countChain(this.param).then(result => {
      let data = result as any;
      if (data.code == 0) {
        this.options.total = data['data'];
      }
    });
}複製程式碼

2.observable的訪問模式

檔案:auth.service.ts
 //需要匯入的檔案
 import { Observable } from 'rxjs/Observable';
 /**
 * observable模式請求
 * @param url 
 * @param body 
 */
httpClient(url: string, body: any): Observable<RequestResult> {
    let headers = this.initAuthHeaders();
    this.spinService.spin(true);
    return this.http.post(
        url,
        AuthService.buildURLSearchParams(body),
        { headers: headers }
    ).map(response => {
        let result = response.json() as RequestResult;
        this.spinService.spin(false);
        return result;
    })
}

檔案:xx.service.ts
/**
 * 連鎖管理:分頁查詢
 * @param param 
 */
 listChain(param: any): Observable<RequestResult> {
    let URL = environment.appmPlusApi + "chain/getChainList";
    return this.service.tt(URL, param).map(result => { return result; })
}

檔案:xx.component.ts
//分頁查詢
searchList() {
    let param = { page: this.page, rows: this.rows, cnName: this.param.cnName };
    this.chainService.listChain(param).subscribe(result => {
    let data = result as any;
      if (data.code == 0) {
        this.dataList = data['data'];
      }
    });
}複製程式碼

相關文章