简体   繁体   中英

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

getUsers(){
this.url = 'http://127.0.0.1:5000/api/users';
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: "admin@gmail.com"
    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() {
  this.getUsers();
}

getUsers(){
  this.userService.getUsers().subscribe(
   data => this.login = data
  );

 console.log(this.login);
 }

what wrong with my code?.

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

getUsers(){
  this.userService.getUsers().subscribe(
   data => {
             this.login = data;
             console.log(this.login);
  }
  );

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM