无法在subscribe()方法中使用订阅值。请帮助如何访问myData out方法。
ngOnInit() {
this.subscription = this.messageService.getMessage().subscribe(function(data){
console.log(data);
this.myData = data;
console.log(this.myData ); // able to print the data
})
console.log(this.myData ); // undefined is printing
this.sampleData = {id: 1080, code: "123"};
}
sample.html
{{myData}} -- [not printing the object] // unable to access inside subscribe method data
{{sampleData}} -- [Printing the object data] // able to access out side subscribe method data
<tr>
<td><label>Location</label></td>
<td><input type="text" maxlength="5" tabindex="1" name="locationCode" [(ngModel)] = myData.location ></td>
</tr>
<tr>
<td><label>Name</label></td>
<td><input type="text" name="txtName" maxlength="10" tabindex="2" [(ngModel)]=myData.name ></td>
</tr>
答案 0 :(得分:2)
您订阅的数据是以异步方式引入的 console.log以同步方式打印。
你需要在订阅中获取数据i:e myData并在那里进行所有处理。
this.subscription = this.messageService.getMessage().subscribe(function(data){
console.log(data);
this.myData = data;
...//do all the processing here
})
答案 1 :(得分:0)
[(ngModel)] = "myData.location"
代替[(ngModel)] = myData.location