gpt4 book ai didi

javascript - 未捕获( promise ): TypeError: Cannot read property 'router' of undefined

转载 作者:行者123 更新时间:2023-11-30 08:26:37 24 4
gpt4 key购买 nike

我正在尝试使用 firebase 服务更新/编辑资源,并且在更新/编辑后我想将其发送回列表组件。

this.firebaseService.updateListing(this.id, listing).then(function() {

this.router.navigate(['/listing/'+this.id]);

});

当我使用下面的代码时,它可以工作,但我想弄清楚为什么上面的代码不起作用。任何帮助将不胜感激。

this.firebaseService.updateListing(this.id, listing);
this.router.navigate(['/listings']);

以下是我使用第一种方法时遇到的错误:

Uncaught (in promise): TypeError: Cannot read property 'router' of undefined

以下是我的路线:

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}

]

下面是我的 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']);
}

}

我查看了与此类似的其他问题,但在我的问题得到答复之前,我不确定这是与“this”上下文相关的问题。

最佳答案

回调内部的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]);
});

关于javascript - 未捕获( promise ): TypeError: Cannot read property 'router' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44521739/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com