Samson Maben
Samson Maben

Reputation: 320

How to make HTTP requests in angular and get the body from the object?

This is the Image of the API request results

Here I am writing a service named FaqService to make HTTP request and calling that service in a component .

getServers(data: string){
    return this.http.get(Staticdata.apiBaseUrl + "/2.2/search/advanced?key="+ Staticdata.key +"&access_token="+ Staticdata.access_token +"&/2.2/search/advanced?order=desc&sort=activity&accepted=True&closed=True&title=" + data + Staticdata.redirectUrl + "&filter="+ Staticdata.filters)
        .map(
        (response: Response) => {
            const items = response.json();
            return items;
        })
    .catch(
        (error: Response) => {
            return Observable.throw(error);
        });
   }
}   

component.ts

  onRecievingResults(value){
    console.log(value);
    this.router.navigate(['results'], {relativeTo: this.route});

    this.faqService.getServers(value)
        .subscribe(
        (item: any[]) => {
            console.log(item);
        },
        (error) => console.log(error)
    ); 
}

Here in this HTML template how do i pass through the API results and get the body.

</div>
<div  class="entryTitle" *ngFor = "let item of items">
<h1>Search results for :{{ item.body }}</h1>
</div>
</div>

Upvotes: 0

Views: 85

Answers (1)

eko
eko

Reputation: 40647

{{ item.body }} will refer to this.item.body in your component. So you'll need to create a field:

public item; // <------- add the field
onRecievingResults(value){
    console.log(value);
    this.router.navigate(['results'], {relativeTo: this.route});

    this.faqService.getServers(value)
        .subscribe(
        (item: any[]) => {
            console.log(item);
            this.item = item; // <------- assign it here
        },
        (error) => console.log(error)
    ); 
}

and change your html to:

<h1>Search results for :{{ item?.body }}</h1>

for a truthy check.

Upvotes: 1

Related Questions