转载[https://www.jianshu.com/p/09beac2c0c99]
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-root',
templateUrl: 'app/app.component.html'
})
export class AppComponent {
constructor(private http: HttpClient) { }
ngOnInit() {
// 发起一个get请求
this.http.get('/api/people/1').subscribe(json => console.log(json));
}
}
注意:上面的this.http.get... 处理HTTP最好放到单独的Service文件中,再注入到Component。这里为了演示没有这么做。
优化有顺序依赖的多个请求
有些时候我们需要按顺序发起多个请求,根据第一个请求返回的结果中的某些内容,作为第二个请求的参数,比如下面代码。
ngOnInit() {
this.http.get('/api/people/1').subscribe(character => {
this.http.get(character.homeworld).subscribe(homeworld => {
character.homeworld = homeworld;
this.loadedCharacter = character;
});
});
}
上面的嵌套写法可读性不那么好,我们可以使用RxJS提供的mergeMap操作符来优化上述代码
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { mergeMap } from 'rxjs/operators';
@Component({
selector: 'app-root',
templateUrl: 'app/app.component.html'
})
export class AppComponent {
homeworld: Observable<{}>;
constructor(private http: HttpClient) { }
ngOnInit() {
this.homeworld = this.http.get('/api/people/1')
.pipe(
mergeMap(character => this.http.get(character.homeworld))
);
}
}
mergeMap 操作符用于从内部的 Observable 对象中获取值,然后返回给父级流对象。
可以合并 Observable 对象
处理并发请求
forkJoin 是 Rx 版本的 Promise.all(),即表示等到所有的 Observable 都完成后,才一次性返回值。
import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { forkJoin } from "rxjs/observable/forkJoin";
@Component({
selector: 'app-root',
templateUrl: 'app/app.component.html'
})
export class AppComponent {
loadedCharacter: {};
constructor(private http: HttpClient) { }
ngOnInit() {
let character = this.http.get('https://swapi.co/api/people/1');
let characterHomeworld = this.http.get('http://swapi.co/api/planets/1');
forkJoin([character, characterHomeworld]).subscribe(results => {
// results[0] is our character
// results[1] is our character homeworld
results[0].homeworld = results[1];
this.loadedCharacter = results[0];
});
}
}