我在authProvider
提供程序类中使用此方法:
getUser() {
return this.afAuth.authState.subscribe(user => {
return user;
});
}
我想在不同的课程中订阅它,例如:
this.authProvider.getUser().subscribe(user => console.log(user));
如何在Observable
方法中返回getUser()
的任何想法?
答案 0 :(得分:7)
您的string username = "user";
string password = "password";
string mongoDbAuthMechanism = "SCRAM-SHA-1";
MongoInternalIdentity internalIdentity =
new MongoInternalIdentity("admin", username);
PasswordEvidence passwordEvidence = new PasswordEvidence(password);
MongoCredential mongoCredential =
new MongoCredential(mongoDbAuthMechanism,
internalIdentity, passwordEvidence);
List<MongoCredential> credentials =
new List<MongoCredential>() {mongoCredential};
MongoClientSettings settings = new MongoClientSettings();
// comment this line below if your mongo doesn't run on secured mode
settings.Credentials = credentials;
String mongoHost = "127.0.0.1";
MongoServerAddress address = new MongoServerAddress(mongoHost);
settings.Server = address;
MongoClient client = new MongoClient(settings);
var mongoServer = client.GetDatabase("myDb");
var coll = mongoServer.GetCollection<Employee>("Employees");
// any stubbed out class
Employee emp = new Employee()
{
Id = Guid.NewGuid().ToString(),
Name = "Employee_" + DateTime.UtcNow.ToString("yyyy_MMMM_dd")
};
coll.InsertOne(emp);
已经是可观察的。只需返回您的authState
并在另一个函数中订阅即可。在任何其他工作的功能中,您可以使用 RxJS#map 功能。
authState
答案 1 :(得分:3)
不要在getUser
功能内订阅。只需返回可见的。
getUser() {
return this.afAuth.authState
}
答案 2 :(得分:3)
你可以这样做。然后在您的组件中,调用此函数的组件,您可以订阅此observable。
getUser(): Observable<any> {
return Observable.create( (observer: Observer<string>) => {
this.afAuth.authState.subscribe(user => {
observer.next(user);
}, (err) => observer.error("error"));
});
}
阿什利
答案 3 :(得分:2)
您需要将返回类型设置为observable
getUser(): Observable<Type> {
return this.afAuth.authState;
});
}
答案 4 :(得分:0)
您可以直接返回该函数并在另一个类中订阅它。
getUser() {
return this.afAuth.authState();
}
您可以将observable视为订阅调用的函数。
this.authProvider.getUser().subscribe(user => console.log(user));