【问题标题】:Angular 5 : Cannot read property 'subscribe' of undefinedAngular 5:无法读取未定义的属性“订阅”
【发布时间】:2019-10-11 17:45:55
【问题描述】:

我已经尝试了很多天来解决 stackoverflow 上的这个错误,因为我现在是 Angular 的新手,所以我只需要向社区询问。我一直在研究 JWT 身份验证

错误类型错误:无法读取未定义的属性“订阅” 在 RawMaterialComponent.loadRawMaterialsByCompany (raw-material.component.ts:774)

我在组件中有如下服务调用

    private loadRawMaterialsByCompany(callback: any) {
    let serviceSubscriptions =this.rawMaterialService.getRawMaterialsByCompany().subscribe(data => {
      this.rawMaterials = data;
      this.rawMaterialLoading = false;
    }, 
     error => this.handleError(error));
    }

服务如下

     getRawMaterialsByCompany() {
        const url = this.raw_material_api_endpoint + 'Company/' + this.company_id;
        return this.get(url);
      }

上面的服务调用重定向到基础服务,它实现了所有的http请求,即:get、post

我在这里要做的是,如果访问令牌已过期,我想刷新令牌。使用发布请求

     protected get(url: string) {
        if (this.isTokenExpired(localStorage.getItem('userToken'))) {

            this.getOriginalDataset(url).then((val)=>{

            this.getTokenfromService()
            return(val)
          });
        } else {
          return this.http.get(url)
            .map(this.extractRequests)
            .catch(this.handleError);
        }


    protected post(url: string, body: any) {
        if (url.includes("RefreshToken") || url.includes("Login") || url.includes("Logout")) {
          return this.http.post(url, body, { headers: this.getHeaders() })
            .map(this.extractRequests)
            .catch(this.handleError);
        }
        else {
            return this.http.post(url, body, { headers: this.getHeaders() })
              .map(this.extractRequests)
              .catch(this.handleError);

        }

      }

**现在我不会为发布请求刷新令牌

getOriginalDataset() 方法为原材料组件带来请求的数据

getTokenfromService() 方法获取新的访问令牌和刷新令牌存储在本地存储中

    sendoriginalDataset(originalUrl):Promise<any>{
        return new Promise(resolve => {
        const dataSet= this.http.get(originalUrl, { headers: this.getHeaders() })
        .map(this.extractRequests)
        .catch(this.handleError);
        resolve(dataSet)
        });
      }

    async getTokenfromService() {

        const base64EncodedJwtAndRefreshToken = btoa(encodeURI(`${localStorage.getItem('userToken')}:${localStorage.getItem('refreshToken')}`));
        const url = this.login_api_endpoints + 'RefreshToken/';
        this.asyncResult = await this.post(url, JSON.stringify(base64EncodedJwtAndRefreshToken))
          .toPromise();
        console.log('First Promise resolved.')
        if (this.asyncResult !== null) {
          localStorage.setItem('userToken', this.asyncResult.jwtToken)
          localStorage.setItem('refreshToken', this.asyncResult.refreshToken)

        }

      }

两种方法都运行正常,但是一旦 getTokenfromService() 执行发布请求,控制台错误就会弹出 Cannot read property 'subscribe' of undefined

每个 http 请求都会发生这种情况,上面是一个示例。非常感谢您的小帮助!

【问题讨论】:

    标签: node.js angular typescript ecmascript-6 rxjs


    【解决方案1】:

    您不能subscribe 承诺。变化:

    this.getOriginalDataset(url).then((val)=>{
    this.getTokenfromService()
    return(val)
    

    收件人:

    return from(this.getOriginalDataset(url)).pipe(
      tap(() => this.getTokenfromService())
    )
    

    【讨论】:

      【解决方案2】:

      你必须使用 await 来获取数据

      await this.getTokenfromService()
      

      如果还有错误请告诉我

      【讨论】:

      • 感谢您的回复,但我不希望从 getTokenfromService() 方法返回任何数据。我要将这些数据保存在本地存储中
      • 我不明白你的意思?我的建议是您使用 await 使您的代码工作,因为您的 getTokenfromService() 方法正在使用 async
      • 如您所见,asyncResult 是一个等待,其数据作为令牌保存在 localStorage 中
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-13
      • 2020-08-05
      • 1970-01-01
      • 2018-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多