看不到对值来自服务的变量进行出价



一开始,我使用一个服务,它给了我一个字符串,我把它保存在变量中,我用大括号在HTML上显示它,但我没有看到值,我已经测试了服务和值来自后端,所以我认为这种情况是由于生命周期。我尝试了ngOnInitngAfterViewInit,但我无法获得值。

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中创建一个公共变量,然后在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 => {
...
});
}

最新更新