【发布时间】:2021-05-02 18:42:15
【问题描述】:
我已经阅读了很多关于如何在 RxJs 和 Angular 中嵌套观察者的文档、文章和不同的线程,但我仍然遗漏了一些东西并且最终无法得到结果。
这是我的代码:
page.ts
export class LiabilitiesPage implements OnInit {
constructor(
private liabilityService: LiabilityService,
private router: Router
) {}
refreshLiabilities() {
// Get the liabilities
console.log('refreshing') // passing there
this.liabilityService.getAllLiabilities().subscribe(
(response: Liability[]) => {
console.log(response); // <=== Never pass there !
if (response) {
this.liabilities = response;
} else {
// empty response code
}
}, error => {
// response error code (never passing there either)
}
}
}
liability.service.ts
// all the needed imports
@Injectable({
providedIn: 'root'
})
export class LiabilityService {
constructor(
private authService: AuthService,
private http: HttpClient,
) {}
// first try : Do not send the http request
getAllLiabilities(): Observable<Liability[]> {
return this.authService.getOptions()
.pipe(
tap(options => this.http.get<Liability[]>(this.url + 'me/', options))
);
}
// try 2 : Doesn't work either
getAllLiabilities(): Observable<Liability[]> {
return this.authService.getOptions()
.pipe(
switchMap(options => this.http.get<Liability[]>(this.url + 'me/', options)), // at this point I tried pretty much every operators (map, mergeMap etc.)
withLatestFrom()
);
}
/* this code was working before that I transformed the authService.getOptions in observable (it was just returning the options synchronyously before)
getAllLiabilities(): Observable<Liability[]> {
return this.http.get<Liability[]>(this.url + 'me/', this.authService.getOptions());
}*/
}
auth.service.ts
public getOptions(): Observable<any> {
return new Observable((observer) => {
this.storage.get('authToken').then((token) => {
console.log('passing') // Pass here
if (token && typeof token.auth_token !== 'undefined') {
console.log('passing') // pass here as well
this.isLoggedIn = true;
this.token = token.auth_token;
}
// it is returning the value
return {
headers: this.headers.set('Authorization', 'Bearer ' + this.token),
params: new HttpParams()
};
})
});
}
我尝试了几乎所有可能的运算符组合以使其在责任服务中工作但没有任何成功。
问题:
问题是我的 page.ts 订阅了 this.http.get<Liability[]>(this.url + 'me/', options) 观察者,但没有触发任何 xhr 请求。 http get 观察者永远不会被执行,我不明白我在那里缺少什么。
我刚刚开始尝试 Angular,但如果我理解正确,操作员应该进行映射和展平,但这看起来永远不会发生。
奖金问题:
我也不明白为什么初始代码:
return this.http.get<Liability[]>(this.url + 'me/', this.authService.getOptions());
正在返回Observable<Liability[]>
并使用 switchMap :
switchMap(options => this.http.get<Liability[]>(this.url + 'me/', options))
它返回一个Observable<HttpEvent<Liability[]>>
如果有人有线索并有时间回答我,那就太棒了
【问题讨论】:
标签: javascript angular typescript rxjs observers