繁体   English   中英

未捕获(承诺):TypeError:无法读取未定义的属性“ router”

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

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

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']);

愚弄是我第一种方法得到的错误:

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]);
    });

尝试在上下文中添加this

this.firebaseService.updateListing(this.id, listing).then(function() {
    this.router.navigate(['/listing/'+this.id]);
}, this); /* <-- here */

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM