简体   繁体   中英

Angular 7 httpClient.post subscribe data is not accessible in the angular template

Tech: Angular 7

I am trying to subscribe to httpClient.post and in the subscribe I am assigning the response to my local model and that local model is being used in the Angular HTML template to display the server response values

In the HTML template the model attributes are empty and are not displaying the assigned server response after subscribe .

However, in the console inside the subscribe I am able to print the model values

My code snippet for controller:

constructor(private httpClient:HttpClient){
this.mymodel = new MyModel();
}

onSubmit() {
this.submitted = true;
// this.mymodel.success  = false; //this.mymodel is my model object
if (this.form.invalid) { //reactive form
  return;
} else {
 const result: model= Object.assign({}, this.form.value);
this.httpClient.post<MyModel>('http://myservice/url/api', result)
.subscribe(
  response => {  this.mymodel = response;
  console.log(this.mymodel.firstname) //this is printing the server response value 
  }
  );
}

}

My code snippet for template (HTML):

<body>
<p>{{mymodel.firstname}}</p>
<p>{{mymodel.lastname}}</p>

Note: The same code is working perfectly in Angular 5.

What am I doing wrong here, what is the missing in my code. Any help is greatly appreciated.

Note: Edited, previously I didn't added {{ in the template.

Change it to :

<p>{{mymodel?.firstName}}</p> <!--{{mymodel?.firstname}}-->
<p>{{mymodel?.lastName}}</p>
  • You are not binding the values to what's declared in your TS part
  • Check your model , whether it is firstname or firstName , could not be both.
  • Separe your services from components, create other injectable classes (services = classes with @Injectable() ) and inject them in your components WHERE you should subscribe on them once inner methods are called.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM