typescript 如何以角度 4 返回 Observable?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46168165/
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 04:52:48  来源:igfitidea点击:

How to return an Observable in angular 4?

angulartypescriptobservablesubscriber

提问by Patrioticcow

I have this method inside a authProviderprovider class:

我在authProvider提供者类中有这个方法:

getUser() {
    return this.afAuth.authState.subscribe(user => {
        return user;
    });
}

I would like to subscribe to it in a different class, something like:

我想在不同的类中订阅它,例如:

this.authProvider.getUser().subscribe(user => console.log(user));

any ideas how to return an Observableinside the getUser()method?

任何想法如何返回方法Observable内部getUser()

回答by Suren Srapyan

Your authStateis already Observable. Just return your authStateand subscribe within another function. In the function for any other work you can use RxJS#mapfunction.

authState已经是 Observable 了。只需返回您的authState并在另一个函数中订阅即可。在用于任何其他工作的函数中,您可以使用RxJS#map函数。

getUser() : Observable {
    return this.afAuth.authState.map(...);
}

....

login() {
   getUser().subscribe(user => {
       return user;
   });
}

回答by Sachila Ranawaka

Don't subscribe inside the getUserfunction. Just return the obsevable.

不要在getUser函数内部订阅。只需返回可观察的。

getUser() {
    return this.afAuth.authState
}

回答by ashley

You can do something like this. Then in your component, the one which is calling this function, you can subscribe to this observable.

你可以做这样的事情。然后在调用此函数的组件中,您可以订阅此 observable。

getUser(): Observable<any> {
    return Observable.create( (observer: Observer<string>) => {
     this.afAuth.authState.subscribe(user => {
        observer.next(user);
    }, (err) => observer.error("error"));
}); 
}

Ashley

阿什利

回答by Dheeraj Kumar

You need to set return type as observable

您需要将返回类型设置为可观察的

getUser(): Observable<Type> {
    return this.afAuth.authState;
    });
}

回答by Yonet

You can return the function directly and subscribe to it in another class.

您可以直接返回该函数并在另一个类中订阅它。

  getUser() {
        return this.afAuth.authState();
  }

You can think of observables as functions that are called by subscribing.

您可以将 observable 视为通过订阅调用的函数。

this.authProvider.getUser().subscribe(user => console.log(user));