2017-06-13 99 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

相关问题