Angular HTTP订阅后ngOnInit中的脚本无法激活
我正在学习,但我似乎找不到解决这个问题的办法。我正在订阅HTTP服务。但是,在订阅之后,之后的所有脚本都不会激活。即使是一个简单的console.log数据也无法激活 如果我这样做,它会起作用:Angular HTTP订阅后ngOnInit中的脚本无法激活,angular,http,observable,Angular,Http,Observable,我正在学习,但我似乎找不到解决这个问题的办法。我正在订阅HTTP服务。但是,在订阅之后,之后的所有脚本都不会激活。即使是一个简单的console.log数据也无法激活 如果我这样做,它会起作用: this._colorsService.returnColorsHttp() .subscribe( (data: any) => { this.colors = data; this.totalColors = data
this._colorsService.returnColorsHttp()
.subscribe(
(data: any) => {
this.colors = data;
this.totalColors = data.length;
this.colorRows = Array.from(Array(Math.ceil(this.totalColors / this.colorItemsPerRow)).keys())
console.log(this.totalColors);
console.log(this.colorRows);
}
);
}
this._colorsService.returnColorsHttp()
.subscribe(
(data: any) => {
this.colors = data;
this.totalColors = data.length;
}
);
this.colorRows = Array.from(Array(Math.ceil(this.totalColors / this.colorItemsPerRow)).keys())
console.log(this.totalColors);
console.log(this.colorRows);
}
但是,如果我这样做,它将失败:
this._colorsService.returnColorsHttp()
.subscribe(
(data: any) => {
this.colors = data;
this.totalColors = data.length;
this.colorRows = Array.from(Array(Math.ceil(this.totalColors / this.colorItemsPerRow)).keys())
console.log(this.totalColors);
console.log(this.colorRows);
}
);
}
this._colorsService.returnColorsHttp()
.subscribe(
(data: any) => {
this.colors = data;
this.totalColors = data.length;
}
);
this.colorRows = Array.from(Array(Math.ceil(this.totalColors / this.colorItemsPerRow)).keys())
console.log(this.totalColors);
console.log(this.colorRows);
}
提前谢谢你 当成功接收到来自服务的响应时,将调用订阅内的代码,直到该响应被阻止,并继续执行订阅下的代码。一旦收到响应,之后它只执行订阅块内的代码
异步任务就是这样工作的 以下内容应放在订阅中:
this.colorRows = Array.from(Array(Math.ceil(this.totalColors /
this.colorItemsPerRow)).keys())
console.log(this.totalColors);
console.log(this.colorRows);
像这样:
this._colorsService.returnColorsHttp()
.subscribe((data: any) => {
this.colors = data;
this.totalColors = data.length;
this.colorRows = Array.from(Array(Math.ceil(this.totalColors /
this.colorItemsPerRow)).keys())
console.log(this.totalColors);
console.log(this.colorRows);
}
);
}第一种方法是访问异步数据的正确方法。在第二种方式中,
当在订阅之外访问时,这个.totalColors
可能是未定义的。这是否意味着它甚至在收到响应之前就开始运行下一个脚本?这就是为什么console.log(this.totalColors);和console.log(this.colorRows);返回未定义?