簡體   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