【问题标题】:Function Inside Subscription - Angular 4订阅内的功能 - Angular 4
【发布时间】:2018-11-23 00:51:36
【问题描述】:

我在调用订阅中的函数时遇到问题。在这个函数中,我调用了一个刷新令牌的订阅,如果返回“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 可以看到:“Unexpected end of input”

【问题讨论】:

  • getLicenseList 将始终返回 licenseList,因为另一个返回语句取决于异步操作

标签: angular rest model-view-controller subscription


【解决方案1】:

你可以使用flapMap来合并observables

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

【讨论】:

    【解决方案2】:
    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 让事情等待。 除了那个伟大的代码!

    【讨论】:

      猜你喜欢
      • 2018-11-26
      • 2018-11-26
      • 2018-05-25
      • 2020-10-11
      • 2018-01-13
      • 2021-11-10
      • 2018-07-13
      • 2017-11-25
      • 2018-08-08
      相关资源
      最近更新 更多