angular - 看不到值来自服务的变量的出价
问题描述
一开始,我使用了一个给我字符串的服务,我将它保存在变量中,并使用大括号在 HTML 上显示它,但我没有看到值,我已经测试了服务并且值来自后端,所以我认为这种情况是由于生命周期。我试过ngOnInit
and 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中创建一个公共变量,然后在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 => {
...
});
}
推荐阅读
- c# - 如何使“Shift + Enter”在文本框中生成新行?
- mysql - Docker Compose Mysql 初始化文件错误(Windows、Dockertoolbox)
- android - 带有可编辑部分的 TextView
- python - CherryPy 如何在获取表单中指定多个“动作”?
- python - TypeError:“lxml.etree._ElementTree”类型的对象没有 len()
- amazon-web-services - AWS 账单显示没有任何主题的 SNS 使用情况?
- maven - 本地系统中需要父子maven结构
- node.js - Nodejs和Typescript找不到模块或进程
- c - 权限被 open() 拒绝
- python - 将forloop给出的字典输出存储在python中