Issue
I would like to display a page from my Backend to my Angular frontend.
Backend: at ‘http://localhost:8080/test‘ I display a simple “hello” text.
Frontend: at ‘http://localhost:4200/editeur‘ there’s a button. When I click on the button, I would like to display my ‘http://localhost:8080/test‘ content under the button (so my “hello” text in this case).
I used a Promise() in Angular.
This is my Express backend middleware:
server.use('/test', (req, res, next) => {
res.json({ message: 'Hello' });
console.log('Hello');
next();
});
This is my HTML frontend:
<button class="btn btn-success" (click)="getEditeur()">Display backend</button>
This is my TS Angular frontend:
getEditeur() {
return new Promise((resolve, reject) => {
this.http.get('http://localhost:8080/test').subscribe(
(response) => {
resolve(response);
},
(error) => {
reject(error);
}
);
});
}
When I click the button, the console.log(‘Hello’); from my backend works, so frontend and backend are well linked. But now I would like my Promise() to display on screen the res.json({ message: 'Hello' });
message.
Thanks !
Solution
you can use async pipe , check this example ๐
component
data = null
i = 1;
getEditeur() {
return new Promise((resolve, reject) => {
// call the api =>
// get the result ...
resolve({ message: 'Hello', times: this.i++ });
});
}
getData() {
this.data = this.getEditeur();
}
template
<button (click)="getData()">Click</button>
<pre>
{{data | async | json}}
</pre>
<ng-container *ngIf="data | async as messageData">
<div>message from server {{messageData.message}} , times {{messageData.times}}</div>
</ng-container>
everytime you click the button will act to give nre promise after this promise resolve the data will be render by json pipe that why I add times property
Without async pipe you can use async/await
async getData() {
this.data = await this.getEditeur();
}
finally you can use promise then method
getData() {
this.getEditeur().then(result=> this.data = result);
}
check this Promise
Answered By – Muhammed Albarmavi
Answer Checked By – David Marino (AngularFixing Volunteer)