2017-11-28 9 views
-1
export class UserComponent implements OnInit { 
    user: {id: number, name: string}; 

    constructor(private route: ActivatedRoute) { } 

    ngOnInit() { 
    // this.user = { 
    // id: this.route.snapshot.params.id, 
    // name: this.route.snapshot.params.name 
    // } 
    this.user.id = this.route.snapshot.params.id; 
    this.user.name = this.route.snapshot.params.name; 
    } 

} 

ここにコードがあります。私はいくつかのデータをユーザーオブジェクトに割り当てようとしています。そして、方法-1でデータを割り当てようとしました。角2+有効なルートパラメータからデータを割り当てます

// method-1 
    this.user.id = this.route.snapshot.params.id; 
    this.user.name = this.route.snapshot.params.name; 

実際には機能しませんでした。しかし、私はもう1つの方法-2を試みましたが、それは方法-1と非常によく似ていて、うまくいきました。私はこれら2つの方法の違いは何かと思います。

// method-2 
    this.user = { 
     id: this.route.snapshot.params.id, 
     name: this.route.snapshot.params.name 
    } 

答えて

0

メソッド-1では、使用した宣言が間違っています。 これは、ユーザーオブジェクトの青いプリントを作成するため、メソッド-1を使用してオブジェクトにデータを格納することはできません。ここで

は、ソリューションです:

user:any = {id: '', name: ''}; 

あなたはユーザーオブジェクトをこのように定義する場合は、あなたの両方の方法-1および方法-2意志が正常に動作します。

関連する問題