SUBHASIS MONDAL
SUBHASIS MONDAL

Reputation: 723

Angular : No Error but not showing data in View

I have very simple code which using Github API. I have no error in my console but data coming to my console but not able to display in View. Somebody, please help me. I am not able to figure it out.

Service Class:

import {
    Injectable
} from '@angular/core';
import {
    Http
} from '@angular/http';
import 'rxjs/Rx';

@Injectable()
export class GithubService {
    constructor(private http: Http) {}
    getUser(searchKey) {

        const url = 'https://api.github.com/search/users?q=' + searchKey;
        return this.http.get(url).map(res => res.json())
    }
}

Method I am calling inside Component.

getUser(value) {
    return this.gitHubService.getUser(value)
        .subscribe(results => {
            this.results = this.results;
            console.log(value);
            console.log(results);

        });
}

and This Is my view html.

<div>
    <br /><br />
    <br /><br /><br /> Enter Value: <input type="text" [(ngModel)]="searchKey">
    <button (click)="getUser(searchKey)">Search</button>
    <ol>
        Data:
        <ul *ngFor="let result of results">
            {{result.login}} {{result.html_url}}
        </ul>
    </ol>
</div>

Upvotes: 2

Views: 6245

Answers (3)

SUBHASIS MONDAL
SUBHASIS MONDAL

Reputation: 723

I have solved the issue as vinod-bhavnani suggested I have added

this.results = results, now it looks-

getUser(value){
 return this.gitHubService.getUser(value)
  .subscribe(results=>{
    this.results=results;
    console.log(value);
    console.log(results);

  });

and

<ul>
    <li *ngFor="let result of results.items">{{result.login}} {{result.html_url}}</li>
</ul>

enter image description here

as I saw My response is coming as Items. So instead of results I have added results.items.

Upvotes: 0

onizukaek
onizukaek

Reputation: 1243

1) Remove .subscribe and let the getUser method return an Observable and assign it to a variable, in your case just call it results$ ($ means this var is an Observable)

getUser(value){
    this.results$ = this.gitHubService.getUser(value);
}

2) In the view side, change your ngFor with:

<ul *ngFor="let result of results$ | async">

Here are some links that should help you to understand: Observable documentation and Angular2 observables example

Upvotes: 2

Vinod Bhavnani
Vinod Bhavnani

Reputation: 2225

There is a problem in your subscribe:

It should be this.results = results instead of this.results = this.results.

You are assigning this.results to itself.

Also, in your template instead of <ul ngFor= "let result of results"></ul> it should be:

<ul>
    <li ngFor="let result of results">{{result.login}} {{result.html_url}}</li>
</ul>

Upvotes: 2

Related Questions