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

标签 javascript angular firebase

我正在尝试使用 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/

相关文章:

元素的 Javascript 选择器/非 CSS 选择器

angular - 从 Angular 2+ 的路由中排除特定路径

angular - 使用 HTML5 的应用程序缓存缓存 Angular2 应用程序

Angular2 对象无法设置未定义的属性

android - firestore 回收器适配器中的 Getitem 方法返回 null

java - 等到 Firebase 查询中的 onChildAdded 完成,Android

javascript - 清除 hide <div> 中的输入值

javascript - 如何在ajax成功中访问对象方法

firebase - 如何将 Apollo Server 2 与 Firebase 功能结合使用

javascript - 如何使用 if 与 $http.post 的数据回调?