2016-09-15 115 views
11

組件的財產採取用戶從服務中使用參數未捕獲的(在承諾):錯誤:無法讀取未定義

@Component({ 
    selector: 'users', 
    providers: [UserService], 
    template: ` 
    <p>{{user.id}}</p> 
` 
}) 
export class UserPageComponent implements OnInit { 
    constructor(
     private userService: UserService, 
     private route: ActivatedRoute 
    ) {}; 

    ngOnInit(): void { 
     this.route.params.forEach((params: Params) => { 
      let id = +params['id']; 
      this.userService.getUser(id) 
       .then(user => {console.log(user.id);this.user = user}) 
     }); 
    } 

服務:

@Injectable() 
export class UserService { 
    private postUrl = 'http://127.0.0.1:8000/user-detail/'; // URL to web api 
    constructor(private http: Http) { 
    } 

    getUser(id: number): Promise<User> { 

     return this.http.get(this.postUrl+id) 
      .toPromise() 
      .then(response => response.json() as User) 
      .catch(this.handleError); 

    }; 

而且我得到錯誤Uncaught (in promise): Error: Error in ./UserPageComponent class UserPageComponent - inline template:1:7 caused by: Cannot read property 'id' of undefined

它看起來就好像該服務沒有發送承諾,儘管它應該。 如何解決這個問題?

回答

20

它看起來像你的組件不到風度有用戶默認值,所以當組件渲染嘗試添加默認值

@Component({ 
    selector: 'users', 
    providers: [UserService], 
    template: ` 
    <p>{{user.id}}</p> 
` 
}) 
export class UserPageComponent implements OnInit { 
    user = {} // default value for user 

    constructor(
     private userService: UserService, 
     private route: ActivatedRoute 
    ) {}; 

    ngOnInit(): void { 
     this.route.params.forEach((params: Params) => { 
      let id = +params['id']; 
      this.userService.getUser(id) 
       .then(user => {console.log(user.id);this.user = user}) 
     }); 
    } 

實際上這將是更好地在這裏加入一些條件邏輯則

它是未定義
<p *ngIf="user">{{user.id}}</p> 

它應該工作

相關問題