组件不会显示来自API的数据

时间:2016-08-30 08:41:37

标签: api angular components angular2-services angular2-http

我正在尝试从我的API加载并显示用户列表,但是当页面加载完成后我的列表不会显示。

我必须进行另一次互动(例如点击按钮)才能显示列表。 view of my example

但是当我从#34; mocks"加载用户时我没有问题

我的组件:



import { Component,ViewEncapsulation, OnInit} 	from '@angular/core';
import { UserService }                          from './services/user.service';
import { User } 							    from './class/user'
import { Observable, BehaviorSubject} 		    from "rxjs";

@Component({
    selector: 'my-app',
    template: `
    <li *ngFor="let user of users" >{{user.username}}</li>
	<span (click) = 'log'>log</span>
    `
})
export class AppComponent {
	users : User[] 

	constructor( private userService: UserService){ }

	ngOnInit(){
		this.userService
		    .getUsers()
		    .then((res) => { 
		                     if (res.users){
                                        this.users = res.users;} 
				    });
	}

	log(){
		console.log(this.users)
	}
&#13;
&#13;
&#13;

我的服务:

&#13;
&#13;
import { Injectable }                 from '@angular/core';
import { Headers, Http, Response }    from '@angular/http'; 
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import { LocalStorage }               from '../class/local-storage';
import { User }                       from '../class/user';

@Injectable()
export class UserService {

    private apiUrl = 'https://localhost:4000/';
    users : User[];
    private token = localStorage.getItem('token');
  
  constructor(private http : Http) {}

  getUsers(){
        return this.http
                   .get(this.apiUrl + 'users?token=' + this.token)
                   .toPromise()
                   .then(res => res.json())
  }
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

<span (click)='log'>log</span> 

应该是

<span (click)='log()'>log</span>

也尝试使用elvis operator,即?,就像这样

<li *ngFor="let user of users" >{{user?.username}}</li>

这意味着只要数据可用,它就会反映变化并且不允许角度显示错误,

如果你有任何问题仍然提供你的plunker plunker和评论这里需要任何问题。