Angular 带rxjs的角度HttpClient
我想用angular 7做一件简单的事情。我只需要调用第一个restapigetKeyrestapi,然后使用返回的键将其传递给第二个restapigetData来获取数据。最后,我希望我的服务返回一个可观察的数据,这样当它完成所有的过程时,我就会得到返回的数据。这是我的代码:Angular 带rxjs的角度HttpClient,angular,rest,rxjs,angular-http,angular-httpclient,Angular,Rest,Rxjs,Angular Http,Angular Httpclient,我想用angular 7做一件简单的事情。我只需要调用第一个restapigetKeyrestapi,然后使用返回的键将其传递给第二个restapigetData来获取数据。最后,我希望我的服务返回一个可观察的数据,这样当它完成所有的过程时,我就会得到返回的数据。这是我的代码: import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders } from '@angular/common/http'; @
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;
})
});
}
}
我知道我做错了,因为我返回的是订阅,而不是可观察的。但就是不知道怎么做。温柔一点,我刚开始玩RxJs,来自AngularJs/promise的背景:)
谢谢
您可以使用
switchMap
来实现这一点-
关于服务部分:
const httpOptions = {
headers: new HttpHeaders({
'Key': key
})
};
getData$(){
return this.http.get("http://myservice/getKey", httpOptions )
}
稍后在组件端:
constructor(private myService: MyTestServiceService ) { }
myMethodToCallMyService() {
this.myService.getData$().subscribe(data => console.log(data));
}
订阅服务类中的。
标题选项
(您可以使用通用服务获取它们),因为您将在每个服务中使用它们,因此它们不应依赖于特定的服务您可以使用
switchMap
实现多个httpClient
调用,并将数据返回为observeable
,您需要熟悉pipe
和map
rxjs操作符
像这样试试
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").pipe(
switchMap(key=>{
return this.http.get("http", headers: new HttpHeaders({
'Key': key
}));
}));
}
}
希望这有帮助-检查此库-快乐编码:)如果您想首先获取密钥,然后在第二次调用中使用它来获取数据,
concatMap
是您的伙伴,因为它依赖于之前的可观察到的数据来完成<如果您希望放弃以前的可观察流,并在以前的流发出值后立即启动一个新流,则代码>开关映射是合适的
因此,要将此应用于您的服务:
getData$(): Observable<whatever you return in api here>{
return this.http.get('getKeyUrl').pipe(
concatMap(key => {
const headers = new HttpHeaders({'Key': key});
return this.http.get('urlTwo', httpOptions)
})
)
}
getData$():可观察{
返回这个.http.get('getKeyUrl').pipe(
concatMap(键=>{
const headers=新的HttpHeaders({'Key':Key});
返回此.http.get('urlTwo',httpOptions)
})
)
}
getData$(): Observable<whatever you return in api here>{
return this.http.get('getKeyUrl').pipe(
concatMap(key => {
const headers = new HttpHeaders({'Key': key});
return this.http.get('urlTwo', httpOptions)
})
)
}