【问题标题】:How to get value from subscribe inside function? Ionic 3如何从订阅内部函数中获取价值?离子 3
【发布时间】:2018-12-22 04:50:52
【问题描述】:

我有这个函数,可以从 URL 获取 JSON 文件。 现在我只需要该文件中的一个随机对象,该对象显然是this.data。 但是当尝试在 .subscribe 函数之外使用 console.log(this.data) 时,我得到了未定义。我需要在函数的其余部分使用该值并将其返回给另一个函数吗?

这是我的代码:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';


/*
  Generated class for the AdsProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/
@Injectable()
export class AdsProvider {
    adsUrl: string;
  constructor(public http: HttpClient) {
    console.log('Hello AdsProvider Provider');
  }
  getAds() {
    this.adsUrl = 'an url';
    console.log(this.adsUrl);
    console.log('I can get ads');
    // Nu vraag je de file van de server
    let data: Observable<any> = this.http.get(this.adsUrl);

    data.subscribe(result => {
      this.data = result;
      // Nu heb je de JSON file met de advertenties
    });
   console.log(this.data); // this gives me undefined
  }
}

【问题讨论】:

    标签: angular typescript ionic3


    【解决方案1】:

    订阅是异步工作的。因此,console.log() 打印“未定义”是很正常的,因为 console.log() 在订阅返回值之前很久就得到处理。

    data.subscribe(result => {
         this.data = result;
         console.log('this.data: ', this.data);
    
        // call methods that work with this.data from here
    });
    

    你必须调用方法,那个过程

    this.data 
    

    ,来自订阅内部。这是 Angular 中的常用方式。您在订阅中等待一个值,并在它提供后立即使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-28
      • 2019-08-02
      • 2016-11-12
      • 2021-10-22
      • 2019-12-15
      • 2018-08-11
      相关资源
      最近更新 更多