Ari*_*ule 7 promise typescript ionic2 angular
我熟悉Angular2,Ionic2,也许我误解了一些东西,但希望得到帮助.
我有一个名为'CurrentUser'的提供程序,用于存储和获取LocalStorage数据.
getProfile(): any {
this.local.get("user-profile").then((profile) => {
var val = JSON.parse(profile);
return val;
});
}
Run Code Online (Sandbox Code Playgroud)
这个函数getProfile()返回一个promise
如果我将此提供程序注入组件中.在从组件调用此函数时,如何在分配数据之前等待解析的承诺?
@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
}
}
Run Code Online (Sandbox Code Playgroud)
首先,你必须this.local.get("user-profile")从getProfile函数返回promise,以便它可以在你调用时链接.此后,您可以getProfile在.then成功回调中从函数返回数据.
getProfile(): any {
return this.local.get("user-profile").then((profile) => {
var val = JSON.parse(profile);
return val;
});
);
Run Code Online (Sandbox Code Playgroud)
另外,一旦你制作ajax就无法获得数据,一旦成功,你就可以获得响应
ngOnInit(): any {
this._currentUser.getProfile().then(
value => { console.log(value) }
)
}
Run Code Online (Sandbox Code Playgroud)