我有如下功能。我试图弄清楚如何将userDetails发送到observer.next()
getUserDetails(userId: string): Observable<GetUserByIdModel> {
const url = `${this.candidateUrl}/Get`;
this._http.get<any>(url + '/' + userId).subscribe((resp) => {
const userDetails: GetUserByIdModel = {
firstname: 'Joyce',
contactChannels: [
{ type: 1, value: 'test@gmail.com' },
{ type: 2, value: '0111111111' }
],
};
})
return new Observable((observer) => {
observer.next(userDetails);
observer.complete();
});
}
当前,即使我将const userDetails:GetUserByIdModel更改为let / var userDetails:GetUserByIdModel,我仍然得到“找不到名称'userDetails'
答案 0 :(得分:1)
您要在此处进行的操作是转换从API调用中获得的响应。最好使用Rxjs map
运算符。方法如下:
import { map } from 'rxjs/operators';
...
getUserDetails(userId: string): Observable < GetUserByIdModel > {
const url = `${this.candidateUrl}/Get`;
return this._http.get < any > (url + '/' + userId).pipe(
map(resp => {
const userDetails: GetUserByIdModel = {
firstname: 'Joyce',
contactChannels: [{
type: 1,
value: 'test@gmail.com'
},
{
type: 2,
value: '0111111111'
}
],
};
return userDetails;
})
);
}
答案 1 :(得分:0)
首先,您希望在收到订阅者的响应时返回用户吗?如果答案是肯定的,那么您可以在subscribe
内添加return,或者您想返回一个新的Observable,因为您已经有人订阅了此Observable,则应执行以下操作:
userDetails: GetUserByIdModel = {};
getUserDetails(userId: string): Observable<GetUserByIdModel> {
const url = `${this.candidateUrl}/Get`;
this._http.get<any>(url + '/' + userId).subscribe((resp) => {
this.userDetails = {
firstname: 'Joyce',
contactChannels: [
{ type: 1, value: 'test@gmail.com' },
{ type: 2, value: '0111111111' }
],
};
})
return new Observable((observer) => {
observer.next(this.userDetails);
observer.complete();
});
}
但是在订阅者内部返回新变量没有意义,返回从订阅者那里得到的响应是有意义的,
observer: Subject<any> = new BehaviorSubject<any>;
getUserDetails(userId: string): Observable<GetUserByIdModel> {
const url = `${this.candidateUrl}/Get`;
this._http.get<any>(url + '/' + userId).subscribe((resp) => {
// Now you emitting new data as soon as possible you get data
this.observer.next(resp);
})
}
在其他地方,您将拥有类似的东西
observer.subscriber(data => {
// and here you'll have data from that observer
console.log(data)
})
下次请更加清楚,如果您有任何疑问,请随时提问。