【发布时间】:2019-06-06 09:28:27
【问题描述】:
我不明白为什么我的对象在 Angular 上的 ngoninit 上总是“未定义”。
我在我的 api 项目上请求我得到正确的回复。
当我console.log 我的对象未定义(ngoninit)但在其他函数中我可以获得值。
我的问题是为什么以及如何在 ngoninit 中获取我的对象。
谢谢
我在邮递员上正确检索了我的回复 其他函数也检索
服务:
getById(id:string):Observable<Grower>{
return this.http.get<Grower>(`${environment.apiUrl}/growers/${id}`);
}
查看模型:
export class GrowerDetails {
adress:string;
zip:string;
city:string;
}
组件:
growerService:GrowerService;
detailsProfil: GrowerDetails;
constructor(private authenticationService: AuthenticationService, growerService:GrowerService,
private formBuilder:FormBuilder) {
this.growerService = growerService;
}
ngOnInit() {
this.detailsProfil = new GrowerDetails();
this.growerService.getById(this.decoded.nameid).subscribe(
(data:Grower) => this.detailsProfil = {
adress: data.adress,
city: data.city,
zip : data.zip
},
error => console.log(error)
);
console.log(this.detailsProfil); // undefinned
onSubmit(){
console.log(this.detailsProfil); // ok
}
邮递员:
{
"lat": 0,
"long": 0,
"description": "test",
"adress": "test",
"zip": "test",
"city": "test"
}
【问题讨论】:
-
因为你的订阅是异步的,你可以在订阅里面进行控制台,你会看到数据
-
我该怎么做?
-
(data:Grower) => { this.detailsProfil = {...}; console.log(...); } -
外部,是的,但是在 observable 回调执行之后。如果您保留两个
console.log语句,您将看到您的原始语句在订阅回调之前被调用。有关详细信息,请参阅重复的问题/答案。
标签: angular subscribe ngoninit