【问题标题】:Angular 4, method executes before constructor initialize valueAngular 4,方法在构造函数初始化值之前执行
【发布时间】:2018-04-26 05:31:44
【问题描述】:

我有 Angular 4 应用程序。 我在服务的构造函数中调用 getCity() 方法来初始化 cityId 属性。我在另一种方法中使用 cityId?例如,getData()。当我尝试在组件中调用 getData() 时,我收到 cityId 未定义的错误。我认为这是因为 getData() 开始执行时 getCity() 没有完成它的执行。 这两种方法都使用 Observables,并返回 Observable。 我用 getCity().concatMap((id) => getData(...)) 解决了它。

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

@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 */
  }

【问题讨论】:

  • 请贴出代码

标签: angular rxjs


【解决方案1】:

取决于getData 是否在进行服务调用,你能说明getData 做了什么吗?如果 getData 正在进行另一个服务调用,您可以使用switchMap。 如果没有,普通的map 应该适合你。

    @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;
    }

【讨论】:

    【解决方案2】:

    你可以在getCity() from service完成后调用getData()方法:

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

    【讨论】:

      【解决方案3】:
      getCity.subscribe(data => console.log(data))
      

      【讨论】:

      • OP 在发布他的问题时做得很糟糕,所以我想我也会这样做
      • 根据他的声誉状况,OP 似乎是新来的,但你不是,所以你有责任提供高质量的答案,不像 StackOverflow 上的新生
      猜你喜欢
      • 2017-06-13
      • 2015-09-15
      • 1970-01-01
      • 1970-01-01
      • 2021-12-21
      • 1970-01-01
      • 1970-01-01
      • 2010-10-01
      • 1970-01-01
      相关资源
      最近更新 更多