Rumes Shyaman Rumes Shyaman - 1 year ago 80
JSON Question

Json Object assign to interface is not working angular2

I'm trying to use http get with observable, I create a service for that and return a object.

my inteface

export interface Login {
login : boolean;
username : string;
type: string;
token: string;
email: string;
name: string;

my service

this.url = '';
return this.callApi(this.url);

callApi(url: string): Observable<Login[]> {
return this.http.get(url).map(this.extractData).catch(this.handleError);

private extractData(res: Response) {
let body = res.json();
// console.log(body['result']);
return body.result || { };

whan i use this service in my component it return object like below.

[Object, Object]
0: Object
email: ""
id: "5788995b008b2f1af2e33f78"
name: "admin"
type: "admin"
user_name: "admin"
__proto__: Object
1: Object
length: 2

when I try to map this onto array of Login object it not working. when I try to get console log on it its shows [] this.

my component

private login : Login[] = [];
mode = 'Observable';

constructor(private userService: UserService) {}

ngOnInit() {

data => this.login = data


what wrong with my code?.

Answer Source

Updated: console.log(this.login); prints an empty array because the promise has not finished, so if you want to print the data array, move that statement inside the subscribe function.

The code should be like this

   data => {
             this.login = data;