2017-07-30 77 views
1

我是新來的角度和開始傾斜的角度4.數據沒有綁定ngfor 指令在組件上使用異步管道。請幫助異步管道可觀察到的角度4

用戶的服務使用HTTP請求從API獲取數據:

import { Injectable } from '@angular/core'; 
import { Http, Response, Headers, RequestOptions } from '@angular/http'; 
import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/do'; 
import 'rxjs/add/operator/catch'; 
import { User } from "../Models/user"; 

@Injectable() 
export class UserService { 
constructor(private http: Http) { } 

get(url: string): Observable<User[]> { 
    return this.http.get(url) 
     .map(response => response.json() as User[]) 
     // .do(data => console.log("All: " + JSON.stringify(data))) 
     .catch(this.handleError); 
} 
private handleError(error: Response) { 
    console.error(error); 
    return Observable.throw(error.json().error || 'Server error'); 
} 
} 

我在這裏使用可觀察的用戶

user.service.ts []接口,用於用戶列表:

user.component.ts

import { Component, OnInit, ViewChild } from '@angular/core'; 
import { UserService } from '../Services/user.service'; 
import { FormBuilder, FormGroup, Validators } from '@angular/forms'; 
import { ModalComponent } from 'ng2-bs3-modal/ng2-bs3-modal'; 
import { User } from '../Models/user'; 
import { DBOperation } from '../Shared/enum'; 
import { Observable } from 'rxjs/Observable'; 
import { Global } from '../Shared/global'; 

@Component({ 
    templateUrl: 'app/Components/user.component.html' 
}) 

export class UserComponent implements OnInit { 
    @ViewChild('modal') modal: ModalComponent; 
    users$: Observable<User[]>; 
    user: User; 
    msg: string; 
    indLoading: boolean = false; 
    userForm: FormGroup; 
    dbops: DBOperation; 
    modalTitle: string; 
    modalBtnTitle: string 

    constructor(private fb: FormBuilder, private userService: UserService) 
    { } 

    ngOnInit(): void { 
    this.userForm = this.fb.group({ 
     Id: [''], 
     UserName: ['', Validators.required], 
     Password: ['', Validators.required], 
     FirstName: ['', Validators.required], 
     LastName: ['', Validators.required], 
     Gender: ['', Validators.required] 
    }); 
    this.LoadUsers(); 
    } 
    LoadUsers(): void { 
     this.indLoading = true; 
     this.users$ = this.userService.get('http://localhost:29712/api/userapi/'); 
     this.indLoading = false; 
    } 
} 

用於異步管道訂閱obs的模板ervable用戶變量:

user.component.html

<div class='panel panel-primary'> 
    <div class='panel-heading'> 
     User Management 
    </div> 
    <div class='panel-body'> 
     <div class='table-responsive'> 
     <div class="alert alert-info" role="alert" *ngIf="indLoading"><img src="../../images/loading.gif" width="32" height="32" /> Loading...</div> 
     <div *ngIf='users && users.length==0' class="alert alert-info" role="alert">No record found!</div> 
     <table class='table table-striped' *ngIf='users && users.length'> 
      <thead> 
       <tr> 
        <th>First Name</th> 
        <th>Last Name</th> 
        <th>Gender</th> 
       </tr> 
      </thead> 
      <tbody> 
       <tr *ngFor="let user of users$ | async"> 
        <td>{{user.FirstName}}</td> 
        <td>{{user.LastName}}</td> 
        <td>{{user.Gender}}</td> 
       </tr> 
      </tbody> 
     </table> 
     <div> 
     </div> 
    </div> 
    <div *ngIf="msg" role="alert" class="alert alert-info alert-dismissible"> 
     <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
     <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> 
     <span class="sr-only">Error:</span> 
     {{msg}} 
    </div> 
</div> 

+1

既然你訂閱了,你不應該需要異步管道。 – DeborahK

+1

你的'/ api/userapi /'請求會執行兩次 – yurzui

+0

我會檢查response => response.json(),因爲IUser []解析爲null。你確定服務響應與你的IUser相同的數據結構嗎? –

回答

0

由於您使用異步。嘗試刪除susbcribe。在您的原始代碼上。這裏有一個類似的video。使用$作爲Observable屬性非常有用...

+1

然後他應該改變這個部分'讓用戶| async'以及模板中。 – yurzui

+0

由於this.users爲'Observable 'Type – Sajan

+0

FYI:https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines - Don類型'IUser'不能分配給Type'Observable '不要把我的接口或_用於私人實例...我通常也把$放在變量的末尾來表明它是可觀察的。所以我會讓用戶的用戶$ |異步並更改類 – JGFMK

0

您的* ngIf問題無法直接檢查您的可觀察長度而無需異步管道。試試這個吧,

*ngIf="(users$ | async)?.length==0" 
+0

但長度爲0意味着沒有數據,它會調用另一個http調用 – yurzui

+0

我會解決異步管道一次通過使用'用戶$ | async as users' – yurzui

+0

爲什麼它調用一個更多的api。當ngOnInit運行時,this.loads函數會觸發,它將調用api。 –