Choppy
Choppy

Reputation: 13

Angular2 @Input and http.get

I'm missing something when passing data from a component to another component. I use @Input to pass the data, that i get from an http.get request. The thing is, i get an error while trying to access an attribute from the passed input while the request hasn't been resolved.

//news.ts
import {Component} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import {Pagination} from './pagination';

@Component({
    selector: 'news',
    templateUrl: 'app/news.html',
    viewProviders: [HTTP_PROVIDERS],
    directives: [Pagination]
})
export class News {

    news = [];

    pagination: Pagination;

    constructor(http: Http) {
        http.get('http://test.com/data')
            .map(res => res.json())
            .subscribe(news => this.news = news);
    }
}

//pagination.ts
import {Component, Input} from 'angular2/core';

@Component({
    selector: 'pagination',
    templateUrl: 'app/pagination.html'
})
export class Pagination {
    // page: int = 1;

    @Input() config;

    constructor() {
        // this.page = this.config.number;
    }
}

//Pagination.html
Page {{config.total}}

config.total generates an error on load. But doing {{config}} seems to work though.

Any ideas ?

Thanks

Upvotes: 1

Views: 918

Answers (3)

Choppy
Choppy

Reputation: 13

@Vlado Tesanovic I just tried the second solution because i might need to handle the data in the constructor. What i did :

//news.ts
    constructor(http: Http) {
        // http.get('http://lechiffonbleu.com:1337/news/test')
        //  .map(res => res.json())
        //  .subscribe(news => this.news = news);

        this.news = new Promise((resolve, reject) => {
            resolve = http.get('http://lechiffonbleu.com:1337/news/test')
                .map(res => res.json())
                .subscribe(news => this.news = news);

            console.log(this.news);
            console.log(resolve);
        });
    }

Well i can't figure out how to resolve the promise correctly so it doesn't throw an error in the @input in pagination.ts

Upvotes: 0

Sasxa
Sasxa

Reputation: 41264

Variable decorated with @Input() is not available in the constructor. You have to wait until Angular resolves the binding and access it later in component's lifecycle:

ngOnInit() {
    this.page = this.config.number;
}

Upvotes: 1

Vlado Tesanovic
Vlado Tesanovic

Reputation: 6424

There are two solutions for this:

You can use Elvis operator in your pagination.html

Page {{config?.total}}

This is from Angular documentation:

The Elvis operator (?) means that the employer field is optional and if undefined, the rest of the expression should be ignored.

Second solution would be to use Async Pipe: https://angular.io/docs/ts/latest/api/common/AsyncPipe-class.html

In this case you would need to rewrite your code.

Upvotes: 1

Related Questions