簡體   English   中英

在Ionic3中訂閱提供程序后,Console.log顯示為未定義

[英]Console.log shows as undefined after subscribing to provider in Ionic3

我正在嘗試使用正在構建的Ionic 3應用程序中的Spotify api獲取數據,但是由於某些原因,當我嘗試console.log數據時,它顯示為未定義。 讓我顯示一些代碼,然后進一步解釋。 這是我的getData():

getData(){
    console.log("getData has been called!!!");
    return this.http.get(this.dataUrl).map((res) => {
        res.json(),
        console.log(res.json())//this works fine
    });
}

上面的代碼工作正常。 它位於稱為“ soundData”的提供程序/服務中。 問題出在下面的代碼上。 當我嘗試console.log數據時,它在我的瀏覽器中顯示為undefined:

ionViewDidLoad(){
    this.soundData.getData().subscribe(
        returnedData=> {
            this.data = returnedData;
            console.log(this.data) //this shows as undefined
        },
        returnedError => {
            this.error = returnedError;
        });
}

我真的看不到我在做什么錯。 看起來一切都應該正常工作,但是由於我是TypeScript和Ionic的新手,所以也許我錯過了一些東西。

您需要從.map return

getData() {
    console.log("getData has been called!!!");
    return this.http.get(this.dataUrl).map((res) => {
        console.log(res.json());//this works fine
        return res.json();
    });
}

更加慣用的方式是使用.do方法單獨執行日志記錄操作,如

getData() {
    return this.http.get(this.dataUrl)
        .map(res => res.json())
        .do(json => console.log(json));
}

您可以簡單地遵循以下模式。

您的服務方式

getData(): Observable<your-data-type>{
       return this.http.get(this.dataUrl).map(res => res.json());
  }

您的訂閱方式

getData(): your-data-type {
   this.soundData.getData().subscribe(
        returnedData => {
            this.data = returnedData;
         },
        err => {},
        () => {}
   );
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM