typescript 在 Angular 2、Ionic 2 中返回承诺值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39788861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:53:33  来源:igfitidea点击:

Returning a promise value in Angular 2, Ionic 2

angulartypescriptpromiseionic2

提问by Arianule

I am familiarizing myself with Angular2, Ionic2 and maybe I am misunderstanding something but was hoping for assistance.

我正在熟悉 Angular2、Ionic2,也许我误解了一些东西,但希望得到帮助。

I have a provider called 'CurrentUser' for the purpose of storing and getting LocalStorage data.

我有一个名为“CurrentUser”的提供程序,用于存储和获取 LocalStorage 数据。

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

this function getProfile()returns a promise

这个函数getProfile()返回一个承诺

If I inject this provider into a component. How would I await the promise to to resolve before assigning the data when calling this function from the component?.

如果我将此提供程序注入到组件中。从组件调用此函数时,如何在分配数据之前等待解决的承诺?

@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
  }
}

回答by Pankaj Parkar

First of all you have to return this.local.get("user-profile")promise from getProfilefunction so that it can chain when you call. Thereafter you can get data returned from getProfilefunction in .thensuccess callback.

首先,您必须this.local.get("user-profile")getProfile函数返回承诺,以便在您调用时可以链接。此后,您可以getProfile.then成功回调中获取从函数返回的数据。

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

Additionally you can't get data as soon as you make an ajax, on success of it you can get the response

此外,您无法在制作 ajax 后立即获取数据,成功后您可以获得响应

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

回答by Omri L

Your function getProfile doesn't return a promise. It returns nothing. You should change it to

您的函数 getProfile 不返回承诺。它什么都不返回。你应该把它改成

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

Now in your component, you can extract the data from your profile promise variable.

现在在您的组件中,您可以从配置文件承诺变量中提取数据。

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