简体   繁体   English

变量无法从订阅方法分配

[英]variable can't assign from subscribe method

Within the method itself Shows the value, but outside it shows undefined message 方法本身内部显示值,但方法外部显示未定义消息

Ubigeo.service.ts Ubigeo.service.ts

 lisProvinciaByDepartamento( ubigeoId: string): Observable<Ubigeo[]> {
    let ubigeo$ = this.http
    .get(`${this.baseUrl}/provincia/${ubigeoId}`, {headers: this.getHeaders()})
    .map(mapUbigeos)
    .catch(handleError);
    return ubigeo$;
}

Detail.component.ts Detail.component.ts

cargaPronvicia(ubigeoId: string) {
    this._ubigeoService
        .lisProvinciaByDepartamento(ubigeoId)
        .subscribe((p) => {
            this.provinciaSeleccionada = p
                .find(item =>
                    item.ubigeoId.substr(2, 2) === ubigeoId.substr(2, 2));
            this.provincias = p;
            console.log(this.provinciaSeleccionada); //2
        });

    console.log(this.provinciaSeleccionada); //1
}

undefined in console 在控制台中未定义

Its because the data retrieval is relatively async when you are using it as observalbes. 这是因为当您将其用作观察对象时,数据检索相对异步 So never use the variable directly, 所以永远不要直接使用变量

Good practices 良好做法

  1. Skip subscription if it is empty. 如果为空,则跳过订阅。

     cargaPronvicia(ubigeoId: string) { this._ubigeoService .lisProvinciaByDepartamento(ubigeoId) //////////////////////////////////////////////////////////////// .skipWhile((p) => p === undefined) //////////////////////////////////////////////////////////////// .subscribe((p) => { this.provinciaSeleccionada = p .find(item => item.ubigeoId.substr(2, 2) === ubigeoId.substr(2, 2)); this.provincias = p; console.log(this.provinciaSeleccionada); //2 }); console.log(this.provinciaSeleccionada); //1 } 
  2. Where ever you are using the subscribed variables, check if it contains data, an example in your case would be 在您使用订阅变量的任何地方,请检查其中是否包含数据,例如

     if(this.provinciaSeleccionada){ console.log(this.provinciaSeleccionada); } 

Update 1: 更新1:

  • Use promises with most care, reason is when you are using promises in constructor, your component will not load until the promise is resolved . 小心使用promise,原因是当您在构造函数中使用promise时,在promise被解决之前,您的组件不会加载
    • By this speed of the application will be as expected. 通过这种速度的应用程序将如预期的那样。
    • Angular2's reactive nature is not utilized. 没有利用Angular2的反应性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM