2017-08-16 28 views
0

我在火力項目以下設置:長度anfularfire 2

- Clients 
    - Client 1 
    - Name 
    - Services 
     - Service 1 
     - Service 2 
    - Client 2 
    - Name 
    - Services 
     - Service 1 
     - Service 2 
     - Service 3 

在這上面我已經提供了客戶端我的組件服務,這是我的組件它實現了服務:

@Component({ 
    selector: 'app-client-list', 
    templateUrl: './client-list.component.html', 
    styleUrls: ['../../dashboard.component.css'], 
    providers: [clientService] 
}) 
export class ClientListComponent implements OnInit { 
    clients: Client[]; 
    dataAvailable: boolean; 
    constructor(private clientService: clientService) { 
    this.dataAvailable = false; 
    this.clientService = clientService; 
    } 
    ngOnInit() { 
    this.clientService.getClients().subscribe(res => { 
     this.clients = res; 
     this.dataAvailable = true; 
    }); 
    } 
    updateSearch(a: string) { 
    this.cientService.getClient(a); 
    } 
} 

而且我這是怎麼表現出來(或者我應該如何)在我HTML

<div *ngIf="dataAvailable"> 
<div id="row" *ngFor="let item of homies"> 
    <span>{{item.name}}</span> 
    <span>{{item.upcomingServices.length}}</span> 
</div> 
</div> 

眼下{{item.upcomingServices.length}}說明不了什麼,它只是留下了空白,我已經嘗試過這兩個變化,但似乎沒有任何工作:

{{(項目。即將推出的服務|異步)。長度}} {{(item.upcomingServices |異步)?.長度}}

第一個給出了這樣的錯誤:

Cannot read property 'length' of null 

,第二個給出了這樣的一個:

InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe' 

這是服務,我用它來獲取客戶:

@Injectable() 
export class ClientService { 
    homies: FirebaseListObservable<Client[]>; 
    subject: BehaviorSubject<any>; 
    constructor(db: AngularFireDatabase) { 
    this.subject = new BehaviorSubject(''); 
    this.clients = db.list('/clients', { 
     query: { 
     orderByChild: 'name', 
     startAt: this.subject 
     } 
    }); 
    } 
    getClients() { 
    this.subject.next(''); 
    return this.clients; 
    } 
    getClient(id: number | string) { 
    this.subject.next(id); 
    return this.clients; 
    } 
} 

任何想法,我怎樣才能得到在HTML內嵌套數組的長度,在這種情況下顯示客戶端時的服務的長度。

+0

請發表您的clientService.getClients();代碼 –

+0

服務結構更新問題 –

+0

嘗試我發佈的答案 –

回答

1

您應該在顯示模板之前訂閱該功能並添加一個條件,如下所示。 聲明布爾變量如下圖所示

dataAvailable:boolean=false; 

和修改ngOnInit方法這樣

this.clientService.getClients().subscribe(res=>{ 
this.clients=res;//res.json() if it is not json already 
this.dataAvailable=true; 
}); 

和修改模板類似下面

<div *ngIf="dataAvailable"> 
    <div id="row" *ngFor="let item of clients " > 
      <span>{{item.name}}</span> 
      <span>{{item.upcomingServices.length}}</span> 
    </div> 
    </div>