Yhlas
Yhlas

Reputation: 421

Http Get on Angular 2, read json

I am trying to get JSON data from api and display its content using angular 2. Conversation Component:

export class ConversationComponent implements OnInit {
    public conversation: any;

    constructor(private conversationsService: ConversationsService,
                private routeParams: RouteParams) { }


    ngOnInit() {
        let id = +this.routeParams.get('id');
        this.conversationsService.getConversation(id)
            .subscribe(
            con => this.conversation = con,
            error => console.log(this.conversation)
            )
    }
}

ComversationsService:

@Injectable()
export class ConversationsService {

    private url = 'https://dev4.aldensys.com/PrometheusWebAPI/api/Conversations/';
    private token = this.storageService.getAuthorizationToken();

    constructor(private http: Http, private storageService: StorageService) { }

    getConversation(id: number) {
        var headers = new Headers();
        headers.append('Authorization', 'Bearer ' + this.token);
        var options = new RequestOptions({ headers: headers });
        return this.http.get(this.url + id, options)
            .map(res => res.json())
            .catch(this.handleError);
    }

    private handleError(error: any) {
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }
}

For some reason this.conversation is undefined. I tried to alert response right after I map it to json on service file: it shows 'object: Object'

Any help will be much appreciated.

Upvotes: 1

Views: 860

Answers (1)

maxisam
maxisam

Reputation: 22745

I see. You problem is the template shows error before the data comes in.

use this

{{conversation?.number}}

in Angular2 it is not that forgivable comparing with Angular1

Here is the reference in the doc

Upvotes: 2

Related Questions