【问题标题】:Uncaught (in promise): TypeError: Cannot read property 'router' of undefined未捕获(承诺):TypeError:无法读取未定义的属性“路由器”
【发布时间】:2017-06-13 12:36:05
【问题描述】:

我正在尝试使用 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”的上下文相关的问题。

【问题讨论】:

标签: javascript angular firebase


【解决方案1】:

回调里面的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]);
    });

【讨论】:

  • 我在 EditListingComponent 的 html 中有一个后退按钮。 <a [routerLink]="['/listings']">Back</a> 但是,当我希望返回带有 foll 代码的特定列表时,它不起作用... <a [routerLink]="['/listing/'+listing.$key]">Back</a>... edit-listing.component.ts 文件的代码在我的问题中.. . 你能解释一下为什么会这样吗.. 我确实可以访问列表的 $key 属性,因为我在 console.log 中看到了它
  • @Nosail Sry,但我对此一无所知。
【解决方案2】:

尝试在上下文中添加this

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

【讨论】:

    猜你喜欢
    • 2019-05-16
    • 2018-05-28
    • 1970-01-01
    • 1970-01-01
    • 2016-08-22
    • 1970-01-01
    • 2018-06-03
    • 2020-09-24
    • 1970-01-01
    相关资源
    最近更新 更多