unable to use subscribe value out side the subscribe() method. Please help how to access the myData out side the method.
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>
The data you subscribe is brought in a asynchronous manner , and the console.log is printed in a synchronous manner.
You need to get the data i:e myData inside the subscribe and do all the processing there .
this.subscription = this.messageService.getMessage().subscribe(function(data){
console.log(data);
this.myData = data;
...//do all the processing here
})
做[(ngModel)] = "myData.location"
而不是[(ngModel)] = myData.location
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.