[英]Biding on a variable which value comes from a service can't be seen
一开始,我使用了一个给我一个字符串的服务,我将它保存在变量中,并使用大括号将它显示在 HTML 上,但我没有看到该值,我已经测试了该服务,该值来自后端,所以我认为情况是由于生命周期造成的。 我尝试了ngOnInit
和ngAfterViewInit
,但我无法获得该值。
elCodigoInterno: string;
ngOnInit() {
this.iniciarFormulario();
this.dataService.getCodigoInterno().subscribe(
//result => this.colaborador.codigoInterno = result,
result => this.elCodigoInterno = result,
error => console.log('error ', error)
);
}
ngAfterViewInit(){
this.dataService.getCodigoInterno().subscribe(
//result => this.colaborador.codigoInterno = result,
result => this.elCodigoInterno = result,
error => console.log('error ', error)
);
}
<label for="codigoInterno">Código Interno </label>
<p>{{elCodigoInterno}} </p>
如果在dataService中创建一个public变量,然后在getCodigoInterno方法中赋值给这个变量,就可以得到你想要得到的值。
我可以举个例子
///// 服务
export class LocationService {
public locationlist: Location[] | any;
public location: Location | any;
constructor(private http: HttpClient) { }
public getAllLocation(): Observable<Location[]> {
return this.http.get<ApiResponse>(environment.locationApiUrl, {}).pipe(
map(
(response: ApiResponse) => {
return this.locationlist = response.content;
}
)
);
}
}
///// 成分
public location;
constructor(private locationService: LocationService) { }
ngOnInit(): void {
this.location = this.locationService.locationlist[0].id;
}
public getAlllocations() {
this.locationService.getAllLocation().subscribe(location => {
...
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.