如何从 Observable 捕获和显示数据?

How to capture and display data from Observable?

我有一个名为 'customer.component.ts' 的组件。 在此组件的视图中,有一个名为 'Search' 的按钮。 我正在做的是在此 'Search' 按钮单击上调用网络 api 方法,该方法从 sql db.

获取数据

为此,我有一个 customer.service.ts 文件,我在其中编写了以下代码 -

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs';
import "rxjs/add/operator/map";
import 'rxjs/add/operator/toPromise'; 
import { Customer, CustomerContact, CustomerHeaderAndContactsResponse, CustomerSearchRequestObjectClass, CustomerHeaderAndContactsResponse_Read } from '../models/customer';

@Injectable()
export class CustomerService {
    constructor(private _http: Http) {

    }

    baseUrl: string = 'http://localhost/SampleApi/api/Customer/';

searchCustomers(custReqObj: CustomerSearchRequestObjectClass): observable<CustomerHeaderAndContactsResponse_Read> {        
                    let headers = new Headers();
                    headers.append('Content-Type', 'application/json; charset=utf-8');
                    return this._http.post((this.baseUrl + 'search-customer'), JSON.stringify(custReqObj), { headers: headers }).map(res => res.json());
                }
}

我的customer.component.ts有搜索点击功能 -

import { Component, OnInit } from '@angular/core';
import { strictEqual } from 'assert';
import { ChangeDetectorRef } from '@angular/core';
import { stringify } from '@angular/core/src/facade/lang';
import { Customer, CustomerContact, CustomerHeaderAndContactsResponse_Read } from '../models/customer';
import { Observable } from 'rxjs/Observable';  
import { CustomerService } from '../services/customer.service';
import { ChangeDetectionStrategy } from '@angular/core/src/change_detection/constants';
import { forEach } from '@angular/router/src/utils/collection';
import { AsyncPipe } from '@angular/common';
import { error } from 'util';
import { parse } from 'path';
import { Subscriber } from 'rxjs/Subscriber';

declare var $: any;

@Component({
    selector: 'customer',
    templateUrl: 'app/customer/views/customer.component.html',
})
export class CustomerComponent implements OnInit {
    constructor(private changeDetectorRef: ChangeDetectorRef, private _custSvc: CustomerService) {      
    }

    ngOnInit() {}



customerSearch: CustomerHeaderAndContactsResponse_Read = new CustomerHeaderAndContactsResponse_Read();

 onCustomerSearchClick(): void {

        this._custSvc.searchCustomers(this.custSearchReqObj).subscribe(
            data => {
                this.customerSearch = data;     
            },
            err => console.log(err, 'error has occurred'),
            () => console.log(this.customerSearch)
        );
console.log(this.customerSearch);
 }

下面是我的模型class -

export class CustomerHeaderAndContactsResponse_Read
{
    custHeader:Customer[];
    custContact:CustomerContact[];
}

Customer 和 CustomerContact class都包含一些属性。

最后是我的模板,我在其中尝试遍历对象 table 行根本不显示任何数据。我也使用过 async (AsyncPipe),但帮助不大。

<tr *ngFor="let custItem of customerSearch.custHeader | async; let rowIndex = index">
                                    <td>
                                        <a (click)="onCustomerItemDetailsClick(custItem.acCustomerName, rowIndex)" class="btn">{{custItem.acCustomerName}}</a>
                                    </td>
                                    <td>{{custItem.acCountryId}}</td>
                                    <td>{{custItem.acAreaId}}</td>
                                    <td>{{custItem.acTel}}</td>
                                    <td>{{custItem.acFax}}</td>
                                    <td>{{custItem.acSalesContact}}</td>
                                    <td>
                                        <a (click)="onCustomerContactItemDeleteClick(rowIndex, 'manage-customer')" class="btn" id="btnIconDelete">
                                            <span class="glyphicon glyphicon-trash"></span>
                                        </a>
                                    </td>
                                </tr>

请帮助,因为我不是无法理解what/where我做错了。 如果需要更多信息,请告诉我。

提前致谢! nitinthombre1991@gmail.com

编辑 -

尝试使用 BehaviorSubject 方法,但现在出现如下错误 -

Observable error

异步管道用于将可观察对象直接绑定到模板。因此,您可以执行以下操作:

data$: Observable<CustomerHeaderAndContactsResponse_Read>;
search$ = new BehaviourSubject<boolean>(true);

ngOnInit() {
  this.data$ = this.search$.switchMap(searchObj => this._custSvc.search...(...));
}

onCustomerSearchClick() {
  this.search$.next(true);
}

模板看起来像这样

<tr *ngFor="let item of data$ | async>...</tr>

所以现在每次点击您的搜索时,它都会向服务发送调用,异步管道负责在模板中显示数据