2017-06-13 94 views
1

我試圖使用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'的上下文有關,直到對我的問題作出迴應爲止。

+0

的可能的複製[如何在回調中訪問正確的\'this \'上下文?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback) – echonax

回答

1

嘗試在上下文中添加this

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

回調內部的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]); 
    }); 
+0

明白了。非常感謝。 – Nosail

+0

我在EditListingComponent的html中有一個後退按鈕。 'Back'但是,當我希望回到特定的列表中使用foll代碼時,它不起作用...'Back'... edit-listing.component.ts文件的代碼在我的問題中。 。你可以請大家澄清,爲什麼這可能是..我有權訪問上市的關鍵財產因爲我看到我的console.log – Nosail

+0

@Nosail Sry,但我對此毫無頭緒。 – Sirko

相關問題