dailybombs
dailybombs

Reputation: 79

Angular2 - Looping out result from PHP/Json

Okey, so I am a Angular n00b. I have went through some guides on how to solve this problem, but I feel like I need some guidance from you after all.

I have managed to create this:

A (click)="checkForList()" on a button sends a http.get-request to my PHP-backend which generates json_encoded data which I have managed to console.log with Angular and that works just fine. Which means; I can receive the data into my Angular app.

My service looks like this:

getProjects() {
    return this.http.get("http://localhost/php-backend.php")
        .map(
            (response: Response) => {
                const data = response.json();
                return data;
            }
        )
        .catch(
            (error: Response) => {
                return Observable.throw("Something went wrong");
            }
        );
}

And I have this constructor in my component

constructor(private GetProjectList: GetProjectList) {}
    checkForList() {
        this.GetProjectList.getProjects()
            .subscribe(
                (projects: any[]) => console.log(projects),
                (error) => console.log(error)
    );
}

Instead of just console.logging the data. I wanna render the data in a *ngFor-loop on the DOM.

Something like this... yeah, you get it :)

<ul>
    <li *ngFor="let projects for projectslist">{{ Name }}</li>
</ul>

I would be glad if you could help me converting my above stuff into something I can render on the DOM :)

Upvotes: 2

Views: 71

Answers (1)

Peter Kota
Peter Kota

Reputation: 8350

First the projectList must be defined on this.

class myComponent {
    public projectList;

    constructor(private GetProjectList: GetProjectList) {}

    checkForList() {
        this.GetProjectList.getProjects()
            .subscribe(
                (projects: any[]) => this.projectList = projects,
                (error) => console.log(error)
            );
    }
}

After that you can render it:

<ul>
    <li *ngFor="let project of projectList">{{ project.name }}</li>
</ul>

Upvotes: 1

Related Questions