2017-06-13 11 views
1

firebaseサービスを使用してリソースを更新/編集しようとしています。更新/編集時にリスティングコンポーネントに送り返したいです。Uncaught(約束):TypeError:未定義のプロパティ 'router'を読み取ることができません

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は、私が最初のアプローチで取得エラーです:

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

ための私のコードです:

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

follは私のルートです

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はこれに似た他の質問を見ましたが、私の質問への回答まではこれが「これ」の文脈に関連する問題であるとは確信できませんでした。

+0

可能な重複だから、基本的に2つのオプションがあります[コールバック内の正しい\ '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

はそれを得ました。おかげでv多く。 – Nosail

+0

私はEditListingComponentのhtmlに戻るボタンを持っています。 'Back'しかし、私はfollコードで特定のリストに戻るには、うまくいきません... 'Back' ... edit-listing.component.tsファイルのコードは私の質問にあります..あなたが私のconsole.logに表示されている$ cofの$ keyプロパティにアクセスすることができます。 – Nosail

+0

@ Nosail Sry、しかし、私はそれについて何の手がかりもありません。 – Sirko

関連する問題