Angular4 / MEAN不会在模板上呈现数据

时间:2017-11-17 11:15:42

标签: angular

我正在学习使用Angular4的MEAN堆栈并遇到问题。我使用服务从node.js获取数据,并由app.component订阅。 记录结果显示正确的输出,然而,在模板上呈现它不起作用。没有警告或任何其他错误,但模板上没有显示数据。

以下是服务

import { Injectable } from '@angular/core';
import { Http,Headers,RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class DataserviceService {
    result:any; 
    constructor(private http:Http) { }
    getusers()
       {
           return this.http.get('/users').map( result => this.result = result.json());
       }
    }

App.component.ts

import { Component } from '@angular/core';
import { DataserviceService } from './dataservice.service';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
    users : Array<any> = [];
    constructor(private dataserv : DataserviceService)
     {
        this.dataserv.getusers().subscribe(function(result)
         {
            this.users = result;
            console.log(result);//result is rightly displayed on the console.
        });
    }
}

这是模板

<div *ngIf="users">
  <h2>Results </h2>
  <ul>
    <li *ngFor="let user of users">{{ user.name }}</li>
  </ul>
</div>

2 个答案:

答案 0 :(得分:1)

呈现模板时,您的users数组为空。您应该阅读有关变更检测,更改检测策略,区域等的内容......但是如果您使用rXjs Subject / BehaviorSubject并且将呈现可观察数据,则组件:

import {BehaviorSubject} from 'rxjs/BehaviorSubject';
import { Observable} from 'rxjs/Observable';
import { Component } from '@angular/core';
import { DataserviceService } from './dataservice.service';

@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
    private usersSubj = new BehaviorSubject<Array<any>>([]);
    users : Observable<Array<any>> = this.usersSubj.Observable();
    constructor(private dataserv : DataserviceService)
     {
        this.dataserv.getusers().subscribe(function(result)
         {
            this.usersSubj.next(result);
            console.log(result);//result is rightly displayed on the console.
        });
    }
}

和模板:

<div *ngIf="users">
  <h2>Results </h2>
  <ul>
    <li *ngFor="let user of users | async">{{ user.name }}</li>
  </ul>
</div>

您的服务也可以返回observable,因此您可以订阅用户直接服务,...

答案 1 :(得分:0)

尝试这样:

使用 * ngIf =“users.length&gt; 0”而不是 * ngIf =“users”

<div *ngIf="users.length > 0">
  <h2>Results </h2>
  <ul>
    <li *ngFor="let user of users">{{ user.name }}</li>
  </ul>
</div>