0
点赞
收藏
分享

微信扫一扫

mergeMap 和 forkJoin 的使用场景

young_d807 2022-04-07 阅读 51
AngularRxJS

mergeMap 和 forkJoin 的使用场景

在Angular项目中,利用 mergeMap 和 forJoin 可以更优雅的处理多个 API 请求嵌套的场景。

优化后:

const getUserInfo = this.http.get('/userInfo');
getUserInfo.pipe(
	map(user => {
		this.user = user;
		return user;
	}),
	mergeMap(user => {
		const getBooks = this.http.get(`/books?userId=${user.id}`);
		const getRecords = this.http.get(`/records?userId=${user.id}`);
		return forkJoin([getBooks, getRecords]);
	})
).subscribe(([books, records]) => {
	this.books = books;
	this.records = records;
});

优化前:

const getUserInfo = this.http.get('/userInfo');
getUserInfo.subscribe(user => {
	this.user = user;
	
	const getBooks = this.http.get(`/books?userId=${user.id}`);
	getBooks.subscribe(books => {
		this.books = books;
	});
	
	const getRecords = this.http.get(`/records?userId=${user.id}`);
	getRecords.subscribe(records=> {
		this.records = records;
	});
});
举报

相关推荐

0 条评论