服务内部功能:
getUserInfo() {
this.af.authState.subscribe(authData => {
let email = authData.email;
let array = this.database.list('registeredUsers', {
query: {
orderByChild: 'email',
equalTo: email
}
}).subscribe(data => {
let userFName = data[0].firstName;
});
});
}
组件:
ngOnInit() {
this.afService.getUserInfo();
}
函数本身效果很好,但如何传递要在组件中使用的let userFName
变量?
答案 0 :(得分:3)
您想要的是将其作为可注射服务。这将允许您从任何组件调用它。
最好创建一个新的返回承诺,一旦解决了database.list调用,就可以解决。
"no"
和您的组件
@Injectable()
export class MyService() {
public userFName;
getUserInfo() {
// return a new promise, which you resolve once you get the data
return new Promise((resolve, reject) => {
this.af.authState.subscribe(authData => {
let email = authData.email;
let array = this.database.list('registeredUsers', {
query: {
orderByChild: 'email',
equalTo: email
}
}).subscribe(data => {
let userFName = data[0].firstName;
// resolve promise with username
resolve(userFName);
});
});
});
}
}
答案 1 :(得分:0)
如果您使用@angular/http
,您的http请求应返回rxjs/Observable
。一旦您订阅它,它就会返回订阅。您无法重新订阅订阅类。
import {Observable} from "rxjs";
@Injectable()
export class MyService() {
public userFName;
getUserInfoPromise():Observable<MyResponseType> {
let someObservable = this.someApi.someRequestPOST(request).mergeMap((response:MyResponsType) => {
//you can process the response data here before components use it
this.userFName = response.userFName;
return new Promise(resolve => resolve(response));
});
return someObservable;
}
}
在您的组件中,只需以这种方式加入订阅链。
this.myService
.getUserInfoPromise(requestData)
.subscribe(
(res: MyResponseType) => {
}, (error) => {
});