2016-09-15 23 views
11

Component đưa người dùng từ dịch vụ với paramscủa router (trong lời hứa): Lỗi: Không thể đọc thuộc tính không xác định

@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}) 
     }); 
    } 

dịch vụ:

@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); 

    }; 

Và tôi nhận được Lỗi Uncaught (in promise): Error: Error in ./UserPageComponent class UserPageComponent - inline template:1:7 caused by: Cannot read property 'id' of undefined

Có vẻ như thể dịch vụ không gửi lời hứa, mặc dù nó nên. Làm thế nào để giải quyết vấn đề này?

Trả lời

20

Dường như thành phần của bạn không ai có giá trị mặc định cho người sử dụng, vì vậy nó là undefined khi thành phần render thử tăng thêm giá trị mặc định

@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}) 
     }); 
    } 

thực sự nó sẽ được tốt hơn để thêm một số logic có điều kiện ở đây sau đó

<p *ngIf="user">{{user.id}}</p> 

nó phải hoạt động

Các vấn đề liên quan