2016-09-30 37 views
7

我熟悉Angular2,Ionic2和 ,可能我誤解了某些內容,但希望得到幫助。在Angular 2中返回承諾值,Ionic 2

我有一個名爲'CurrentUser'的提供者用於存儲和獲取LocalStorage數據。

 getProfile(): any { 
     this.local.get("user-profile").then((profile) => { 
     var val = JSON.parse(profile); 
     return val; 
    }); 
} 

此功能。如果我注入此提供到一個組件getProfile()返回一個承諾

。在從組件調用此函數時,如何在分配數據之前等待解決的承諾?

@Component({ 
    templateUrl: 'build/pages/book_meeting/book_meeting.html' 
}) 
export class BookMeetingPage implements OnInit { 
constructor(public navCtrl: NavController, private _currentUser: CurrentUser) { 
} 

profile: IProfile; 

    ngOnInit(): any { 
    this.profile = this._currentUser.getProfile(); 
    console.log(this.profile);//returns undefined 
    } 
} 

回答

9

你必須從getProfile函數返回this.local.get("user-profile")承諾,使其能鏈,當你的第一個停靠。此後,您可以從getProfile函數返回.then成功回調的數據。

getProfile(): any { 
    return this.local.get("user-profile").then((profile) => { 
     var val = JSON.parse(profile); 
     return val; 
    }); 
); 

另外,你不能只要你做一個Ajax獲取數據,在它的成功,你可以得到的迴應

ngOnInit(): any { 
    this._currentUser.getProfile().then(
    value => { console.log(value) } 
    ) 
} 
+0

您好,我得到的錯誤app.bundle.js: 44529 EXCEPTION:錯誤:未捕獲(承諾):TypeError:無法讀取未定義的屬性'then'。 – Arianule

+0

@Arianule抱歉,我在回答中提到,但忘記在代碼部分更改同樣的東西,我的壞。感謝您的支持。檢查更新的代碼 –

+0

嗨那裏Pankaj。你有沒有更新代碼,對不起。我應該返回一個Promise ...沿Promise.resolve(val)返回的行嗎? – Arianule

0

您的函數getProfile不返回承諾。它什麼都不返回。 您應將其更改爲

getProfile(): any { 
    return this.local.get("user-profile").then((profile) => { 
    var val = JSON.parse(profile); 
    return val; 
}); 

現在在你的組件,你可以從你的個人資料的諾言變量提取數據。

ngOnInit(): any { 
    this._currentUser.getProfile().then(value => { 
     console.log(value); //returns your value. 
    }