如何在* ngFor上使用Observable的内部数组?

时间:2017-06-15 01:06:30

标签: angular typescript

以前我有一个表示用户属性的简单对象,但是当我需要向表格可视化添加分页时,我创建了一个视图模型类,其成员类型为User(我的模型)。这是代码:

users-grid.ts(查看模型)

import { User } from "../../models/user";

export class UsersGrid {
    rowCount: number;
    pageCount: number;
    pageSize: number;
    page: number;
    data: Array<User>;
}

user.ts(model)

import { Role } from "./role";

export class User {
    id: number;
    name: string;
    username: string;
    role: Role;
}

然后我在我的服务中使用这些类:

import { Injectable } from '@angular/core';
import { Headers, Http, Response } from "@angular/http";
import { UsersGrid } from "../viewModels/users/users-grid";
import { environment } from '../../environments/environment';

import 'rxjs/add/operator/toPromise';

@Injectable()
export class UsersSearchService {

    private baseUrl = `${environment.apiUrl}/api/users`;  // URL to web api

    constructor(private http: Http) { }

    search(term): Promise<UsersGrid> {
        console.log("A");
        return this.http
            .get(this.baseUrl)
            .toPromise()
            .then((response) => {
                console.log("B")
                return response.json() as UsersGrid;
            })
            .catch(this.handleError);
    }

    private handleError(error: any): Promise<any> {
        console.error('An error occurred', error);
        return Promise.reject(error.message || error);
    }
}

我的组件消耗了它:

import { Component, OnInit, AfterViewInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { Router } from '@angular/router';
import { UsersSearchService } from "./users-search.service";
import { UsersGrid } from "../viewModels/users/users-grid";

import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';

@Component({
    templateUrl: 'users-search.component.html',
    providers: [UsersSearchService]
})
export class UsersSearchComponent implements OnInit, AfterViewInit {

    users: Observable<UsersGrid>;
    private searchTerms = new Subject<string>();

    constructor(
        private usersSearchService: UsersSearchService,
        private router: Router
    ) { }

    search(term: string): void {

        // Push a search term into the observable stream.
        this.searchTerms.next(term);
    }


    ngOnInit(): void {
        this.users = this.searchTerms
            .debounceTime(300)        // wait for 300ms pause in events
            .distinctUntilChanged()   // ignore if next search term is same as previous
            .switchMap(term => this.usersSearchService.search(term))
            .catch(error => {
                // TODO: real error handling
                console.log(`Error in component ... ${error}`);
                return Observable.of<UsersGrid>();
            });


    }

    ngAfterViewInit(): void {
        this.search("");
    }
}

问题是在添加视图模型类并更改组件中的用户变量类型(最后一个代码块)后,服务方法未执行(未执行console.log(“A”))。

我不能像我的视图模型那样使用复杂类型作为可观察对象吗?

更新

我想我找到了这个问题的原因,所以我正在更新问题标题,因为我还在寻找修复。

当我尝试使用*ngFor时,问题似乎与users.data属性有关,因为如果删除.data,则会调用该服务但会导致错误,如果我添加它返回时,不会调用该服务,也不会显示错误消息。

<tr *ngFor="let user of users.data | async">
  <td>{{user.name}}</td>
  <td>{{user.username}}</td>
  <td>{{user.role.description}}</td>
</tr>

1 个答案:

答案 0 :(得分:0)

我找到了解决方法。这就是我必须做的事情:

<tr *ngFor="let user of (users | async)?.data">
  <td>{{user.name}}</td>
  <td>{{user.username}}</td>
  <td>{{user.role.description}}</td>
</tr>