【发布时间】:2019-10-14 23:00:12
【问题描述】:
最近我被转移到一个新项目,该项目使用 Angular 6 作为前端框架和用于 REST 服务的 spring。
该项目已经开发了 2 年,我观察到几乎所有使用 angular HttpClient 发出的 HTTP 请求都通过管道从 rxjs 获取过滤器。所有 REST API 只发出一个值。不需要手动取消,也不需要 observables 的惰性属性。
我的直觉是使用 toPromise() 会是一种更好的编码方式。
你有什么想法?
//customer-service.ts
constructor(private http: HttpClient) {
}
public getCustomers() {
return http.get('/customers');
}
//component.ts
public ngOnInit() {
this.customerService.getCustomers().pipe(take(1)).subscribe((customers) => {
//do some stuff
})
}
我建议的方法:
//customer-service.ts
constructor(private http: HttpClient) {
}
public getCustomers() : Promise<Array<Customer>> {
return http.get('/customers').toPromise();
}
//component.ts
public ngOnInit() {
this.customerService.getCustomers().then((customers: Array<Customer>) => {
//do some stuff
})
}
我认为我的方法更好,因为它是强类型的并且更干净。
【问题讨论】:
-
两者都是强类型,Angular 的其余部分使用 Rx,所以没有。
-
可读性怎么样?你会喜欢
.pipe(take(1)).subscribe()或.then()吗?计算速度方面的效率如何? -
您知道您也可以使用
pipe(take(1))吗?而且你甚至不必take(1)因为http observable 在发射后完成。所以它只是subscribe与then。但是 observables 更常用也更灵活。 -
我明白了。还有一个问题:如果“http observable 在发出后完成”我还需要取消订阅吗?
-
不,你没有。您可以保存订阅并自己与
.isUnsubscribed核对。
标签: javascript angular typescript rxjs observable