Angular的HTTP订阅方法未正确分配实例变量

时间:2019-04-11 10:03:16

标签: angular typescript subscribe

 private getAllData(): void {
    this.stamm_solvara_jahrService.getAll().subscribe(resp => {
        const keys = resp.headers.keys();
        this.headers = keys.map(key=> `${key}: ${resp.headers.get(key)}`);
        this.stamm_solvara_jahrData = {...resp.body};

        console.log('Data inside method');
        console.log(this.stamm_solvara_jahrData);
        console.log('Header inside method'); 
        console.log(this.headers);
    });
    console.log('Data outside method');
    console.log(this.stamm_solvara_jahrData);
    console.log('Header outside method');
    console.log(this.headers);
}

因此在订阅“进程”内部,实例变量this.stamm_solvara_jahrDatathis.headers都具有值。除此之外,它们都是空的。如何解决这个问题?

2 个答案:

答案 0 :(得分:3)

this.stamm_solvara_jahrService.getAll()是一种异步方法,因此必须在其上调用subscribe

因此,将在执行您的订阅回调时定义this.stamm_solvara_jahrDatathis.headers,但是其余代码(订阅之外)无需等待 >为此,它只会尝试打印这两个变量,它们仍然是undefined

我强烈建议阅读有关asynchronous vs synchronous code的内容,以更好地理解为什么这种事情会以javascript之类的语言发生。

答案 1 :(得分:1)

这是正确的,因为subscribe块之外的变量是EMPTY,导致您执行了ASYNC CALL(AJAX),因此您的代码之外订阅将在请求返回之前执行。一旦调用返回(成功与否),执行的代码将是.subscribe函数内的代码,因此

    this.stamm_solvara_jahrService.getAll().subscribe(resp => {
            const keys = resp.headers.keys();
            this.headers = keys.map(key=> `${key}: ${resp.headers.get(key)}`);
            this.stamm_solvara_jahrData = {...resp.body};

            console.log('Data inside method');
            console.log(this.stamm_solvara_jahrData);
            console.log('Header inside method'); 
            console.log(this.headers);
        }); 

P.S如果您还想捕获,则错误响应会将新函数设置为您订阅函数的第二个自变量:

  this.stamm_solvara_jahrService.getAll().subscribe(resp => {
            const keys = resp.headers.keys();
            this.headers = keys.map(key=> `${key}: ${resp.headers.get(key)}`);
            this.stamm_solvara_jahrData = {...resp.body};

            console.log('Data inside method');
            console.log(this.stamm_solvara_jahrData);
            console.log('Header inside method'); 
            console.log(this.headers);
        }, 
(error)=>{ // <-- this one func catch the error from server
console.log(error)
}); 

希望对您有帮助!