我試圖使用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 \'上下文?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – echonax