功能内部订阅 - Angular 4

时间:2018-06-13 12:24:55

标签: angular rest model-view-controller subscription

我在订阅中调用函数时遇到问题。在这个函数中,我调用一个刷新令牌的订阅,如果这返回" true"然后我调用相同的函数,但此操作不起作用。

主要功能:

 getLicenseList():Observable<License[]>{
    let licenseList:License[] =[];
    return this._http.get("license/list").map(res => {
        let processedData = res;
        if(processedData['status'] == "401"){
            this._http.refreshToken().subscribe(result => {
                this.getLicenseList();
            });
        }else{
            for(let license of processedData['data']){
                const obj = new License(license['name'],license['start_date'],license['expire_date'], license['type'], license['duration'],license['id'],license['id_user'], license['projectsList']);
                licenseList.push(obj);
            }
            return licenseList;
        }
    });

}

刷新令牌的功能:

refreshToken():Observable<boolean>{
    let url = 'auth/refresh/self';
    return this.post(url, localStorage.getItem('refresh_token')).map(data => {
        if(data['access_token'] != null || data['refresh_token'] != null){
            window.localStorage.setItem('access_token', data['access_token']);
            window.localStorage.setItem('refresh_token', data['refresh_token']);
            return true;
        }
    }).catch(error =>Observable.throw("Expired refresh token"));
}

在调试模式下进入res我可以看到:&#34;意外的输入结束&#34;

2 个答案:

答案 0 :(得分:0)

您可以使用flapMap合并observables

 return http.get(req1)
      .flatMap(resp => {
        // whatever you need
        return this.http.post(req2);
      })

答案 1 :(得分:0)

getLicenseList():Observable<License[]>{
    let licenseList:License[] =[];
    return this._http.get("license/list").map(async res =>{
            let processedData = res;
            if(processedData['status'] == "401"){
                this._http.refreshToken().subscribe(result =>{ if(result){ return this.getLicenseList();} });
            else{
            for(let license of processedData['data']){
                const obj = new License(license['name'],license['start_date'],license['expire_date'], license['type'], license['duration'],license['id'],license['id_user'], license['projectsList']);
                licenseList.push(obj);
            }
            return licenseList;
        }
    });

}

我看到你将一堆变量传递给构造函数。我建议传递整个对象并让构造函数处理解析。 在observable中使用async和await来使事情等待。 除了那个伟大的代码!!