未捕获(承诺):TypeError:无法读取未定义的属性'路由器'
问题描述:
我试图使用Firebase服务更新/编辑资源并更新/编辑时我想将其发送回列表组件。未捕获(承诺):TypeError:无法读取未定义的属性'路由器'
this.firebaseService.updateListing(this.id, listing).then(function() {
this.router.navigate(['/listing/'+this.id]);
});
当我使用foll代码,它的工作原理,但我想弄清楚为什么上述不起作用。任何帮助将不胜感激。
this.firebaseService.updateListing(this.id, listing);
this.router.navigate(['/listings']);
的FOLL是我第一种方法得到的错误:
Uncaught (in promise): TypeError: Cannot read property 'router' of undefined
的FOLL是我的路线:
const appRoutes: Routes = [
{path:'', component:HomeComponent},
{path: 'listings', component:ListingsComponent},
{path: 'listing/:id', component:ListingComponent},
{path: 'edit-listing/:id', component:EditListingComponent},
{path: 'add-listing', component:AddListingComponent}
]
而且FOLL是我EditListingComponent
代码export class EditListingComponent implements OnInit {
id:any;
checklist:any; /*ngmodel binds the html fields to the properties in the component*/
notes:any;
constructor(private firebaseService: FirebaseService, private router:Router, private route:ActivatedRoute) { }
ngOnInit() {
// Get ID
this.id = this.route.snapshot.params['id'];
this.firebaseService.getListingDetails(this.id).subscribe(listing => {
this.checklist = listing.checklist;
this.notes = listing.notes;
console.log(listing);
});
}
onEditSubmit(){
let listing = {
checklist: this.checklist,
notes: this.notes
}
this.firebaseService.updateListing(this.id, listing).then(function() {
this.router.navigate(['/listing/'+this.id]);
});
/*this.firebaseService.updateListing(this.id, listing);
this.router.navigate(['/listings']);
}
}
I'v e查看了与此类似的其他问题,但我不确定这是否与'this'的上下文有关,直到对我的问题作出回应为止。
答
尝试在上下文中添加this
:
this.firebaseService.updateListing(this.id, listing).then(function() {
this.router.navigate(['/listing/'+this.id]);
}, this); /* <-- here */
答
回调内部的this
参数是不一样之外。所以,你有两种基本选择:
1)添加引用this
:
let self = this;
this.firebaseService
.updateListing(this.id, listing)
.then(function() {
self.router.navigate(['/listing/'+this.id]);
});
2)使用箭头函数(不要保存当前this
上下文):
this.firebaseService
.updateListing(this.id, listing)
.then(() => {
this.router.navigate(['/listing/'+this.id]);
});
的可能的复制[如何在回调中访问正确的\'this \'上下文?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – echonax