Angular 方法在构造函数初始化值之前执行

Angular 方法在构造函数初始化值之前执行,angular,rxjs,Angular,Rxjs,我有四个申请表。 我在服务的构造函数中调用getCity()方法来初始化cityId属性。我在另一种方法中使用cityId?例如,getData()。当我试图在组件中调用getData()时,我收到一个错误,cityId未定义。我认为这是因为getCity()在getData()开始执行时没有完成它的执行。 这两种方法都是使用可观察的和返回可观察的。 我用getCity()解决了这个问题 你能告诉我这是正确的方法吗?也许还有更正确的方法 @Injectable() export class Cu

我有四个申请表。 我在服务的构造函数中调用getCity()方法来初始化cityId属性。我在另一种方法中使用cityId?例如,getData()。当我试图在组件中调用getData()时,我收到一个错误,cityId未定义。我认为这是因为getCity()在getData()开始执行时没有完成它的执行。 这两种方法都是使用可观察的和返回可观察的。 我用getCity()解决了这个问题

你能告诉我这是正确的方法吗?也许还有更正确的方法

@Injectable()
export class CustomService {

  cityId: number;

  constructor(private http: HttpClient,
              private citiesService: CitiesService) {
    this.getCityId()
  }

  getCityId() {
    return this.citiesService.getCity().subscribe(
      (city) => {
        this.cityId = city['id']
      });
  }

  getData() {
    /* use this.cityId here */
  }

您可以在服务的
getCity()
完成后调用
getData()
方法:

getCityId() {
  return this.citiesService.getCity().subscribe({
    next: (city) => {
      this.cityId = city['id'];
    }, 
    complete: () => {
      this.getData();
    }
  });
}

取决于
getData
是否正在进行服务呼叫,能否显示
getData
的功能?。如果getData正在进行另一个服务调用,则可以使用
switchMap
。 如果没有,常规的
地图应该适合您

    @Injectable()
    export class CustomService {

    constructor(private http: HttpClient,
                private citiesService: CitiesService) {
    }

    getCityId() {
        return this.citiesService.getCity()
    }

    getDataAsynchronous() {
        return this.getCityId()
            .map(city => city.id)
            .switchMap(id => this.service.serviceCall())
    }

    getDataSynchronous() {
        return this.getCityId()
            .map(city => city.id)
            .map(id => processID(id))
    }

    processID(id: string) {
        // do something with id
        return id;
    }

发布代码,请发布OP的问题做得很糟糕,所以我想我也会这么做。根据他的声誉状况,OP是新来的,但你不是,所以你有责任提供高质量的答案,而不是像StackOverflow上的新生一样
    @Injectable()
    export class CustomService {

    constructor(private http: HttpClient,
                private citiesService: CitiesService) {
    }

    getCityId() {
        return this.citiesService.getCity()
    }

    getDataAsynchronous() {
        return this.getCityId()
            .map(city => city.id)
            .switchMap(id => this.service.serviceCall())
    }

    getDataSynchronous() {
        return this.getCityId()
            .map(city => city.id)
            .map(id => processID(id))
    }

    processID(id: string) {
        // do something with id
        return id;
    }