加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular – 如何避免RxJs订阅回调地狱?

发布时间:2020-12-17 07:07:10 所属栏目:安全 来源:网络整理
导读:我正在使用Angular RxJs订阅进行HttpClient调用,然后使用第一个调用的值进行另一个调用.在这种情况下,有一个获取地址对象的调用,然后我使用这个对象进行调用.像这样: @Injectable()export class AddressService { constructor(private http: HttpClient) {
我正在使用Angular RxJs订阅进行HttpClient调用,然后使用第一个调用的值进行另一个调用.在这种情况下,有一个获取地址对象的调用,然后我使用这个对象进行调用.像这样:

@Injectable()
export class AddressService {
  constructor(private http: HttpClient) { }

  getById(addressId: string,userId: string) {
    return this.http.get(BACKEND_URL + 'getAddressById/' + [addressId,userId]);
  }
}
  
export class AddressModalComponent implements OnInit {
  constructor(private alertService: AlertService,private addressService: AddressService,@Inject(MAT_DIALOG_DATA) public data: any,private dropdownService: DropdownService)

  ngOnInit() {
    this.addressService.getById(this.data.id,this.data.userId)
        .subscribe(
          (address: Address) => {
            this.dropdownService.getCidadesBrByEstado(address.name)
              .subscribe((cities: BrCity[]) => {
                this.cities = cities;
                this.address = address;
              },error => console.log(error));
          },error => { this.alertService.error(error);
          }
        );
    }
  }
}

我试图避免多个订阅,在我的代码中有很多这样的.我需要像Node.js promises这样的Async / Await方法,但是在组件级别使用Observables.我对RxJs命令不太熟悉…有没有更好的方法只用一个订阅和catch来进行多次调用?

解决方法

尝试类似的东西:

import { map,switchMap } from 'rxjs/operators'

this.addressService.getById(this.data.id,this.data.userId).pipe(
  switchMap(address => this.dropdownService.getCidadesBrByEstado(address.name).pipe(
    // this pass both cities and address to the next observable in this chain
    map(cities => ({ cities,address }))
  ))
).subscribe(({ cities,address }) => {
  this.cities = cities
  this.address = address
})

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读