简体   繁体   中英

Angular 4 - printing response from onInit in html

I have ngOnInit function in .ts class, and html file associated with it.

    ngOnInit() {
//some code
}.then(response => {
          console.log(response.data.reports[0].reportStatus);
         //some other code
})

generally the method works fine, and the log prints accurate results, but I tried many things and I don't know how to pass the response(and its fields) to html file so that I can print that. Thx for help!

Well there are a few ways. You could just have a variable. For example:

yourVariable: string;

ngOnInit() {
//some code
}.then(response => {
          console.log(response.data.reports[0].reportStatus);
         this.yourVariable = response.data.reports[0].reportStatus;
})

Then in your HTML:

<p>My data is: {{ yourVariable }}</p>

This is the very basics of Angular. You should at least read the documentation before asking questions.

.then(response => {
   console.log(response.data.reports[0].reportStatus);
   this.status = response.data.reports[0].reportStatus;
   //some other code
})

// HTML

<span>{{ status }}</span>

Initialize a variable dataToDisplay to which you will assign the result from the Promise.

  dataToDisplay;  
      ngOnInit() {
    //some code
    }.then(response => {
              console.log(response.data.reports[0].reportStatus);
             this.dataToDisplay = response.data.reports[0].reportStatus;
    })

And in the HTML just bind the dataToDisplay property like this

<h1 *ngIf="dataToDisplay"> {{dataToDisplay}} </h1>

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