我正在尝试在 Angular 7 中做一件简单的事情。我只需要调用第一个 getKey REST api,然后使用返回的 key 将其传递给第二个 REST api getData 获取我的数据。最后,我希望我的服务返回一个 Observable,这样当它完成所有过程时,我就可以获得返回的数据。这是我的代码:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class MyTestServiceService {
constructor(private http: HttpClient) { }
getData$(){
return this.http.get("http://myservice/getKey").subscribe((key : string) => {
const httpOptions = {
headers: new HttpHeaders({
'Key': key
})
};
return this.http.get("http", httpOptions).subscribe(data => {
return data;
})
});
}
}
我知道我做错了,因为我返回的是订阅而不是 Observable。但就是不知道该怎么做。温柔点,我刚刚开始玩 RxJs,并且来自 AngularJs/promise 背景:)
谢谢
最佳答案
You can use
switchMap
to achieve this -
getData$(){
return this.http.get("http://myservice/getKey").pipe(
switchMap(key=>{
const httpOptions = {
headers: new HttpHeaders({
'Key': key
})
};
return this.http.get("http", httpOptions);
})
);
}
关于带有 rxjs 的 Angular HttpClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53265225/