![](/img/trans.png)
[英]Callback generates “TypeError: this is undefined” in Angular2/Firebase
[英]TypeError: self.context.newUser is undefined on Angular2
當我嘗試在模板上添加輸入字段時,我得到此錯誤TypeError: self.context.newUser is undefined
這是組件
import { Component } from '@angular/core';
import { OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { User } from './user';
import { UserService } from './user.service';
@Component({
selector: 'vista3',
templateUrl: 'app/vista3.component.html',
styleUrls:['app/vista3.component.css']
})
export class Vista3Component implements OnInit{
users: User[] = [];
newUser: User;
constructor(
private router: Router,
private userService: UserService) {
}
ngOnInit(){
this.userService.getUsers().then( users => this.users = users);
}
}
模板
<div class="separar">
<table class="table table-striped">
<tr>
<th>Nombre</th>
<th>Apellido</th>
</tr>
<tr *ngFor="let user of users">
<td>{{user.name}}</td><td>{{user.lastName}}</td>
</tr>
</table>
</div>
<div class="separar">
<div class="row">
<div class="col-xs-12 col-md-3">
Nombre: <input [(ngModel)]="newUser.name"/>
</div>
</div>
</div>
和用戶類
export class User{
name: string;
lastName: string;
}
我不知道我錯過了什么,angular2和打字稿對我來說是新的,如果有人能看到問題......
看起來你沒有為newUser
類成員分配任何東西。
行[(ngModel)]="newUser.name"
中的觸發錯誤。
你試圖從undefined
得到name
。 我建議使用?.
運營商。
<input [(ngModel)]="newUser?.name"/>
並在構造函數中創建一個空用戶:
constructor(
private router: Router,
private userService: UserService) {
this.newUser = new User;
}
您需要先使用newUser
來執行newUser.name
你可以像intiliaze一樣
newUser: User = new User();
並通過添加構造函數來更改User類
export class User{
constructor(
public name?: string,
public lastName?: string
) { }
}
希望這會有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.