Uncaught (в обещании): TypeError: Невозможно прочитать свойство 'router' из неопределенного

1

Я пытаюсь обновить/изменить ресурс с помощью службы 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']); 
  }

}

Я рассмотрел другие вопросы, подобные этому, но я не был уверен, что это проблема, связанная с контекстом "этого", до ответов на мой вопрос.

Теги:
angular
firebase

2 ответа

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
    понял. спасибо большое.
  • 0
    У меня есть кнопка "Назад" в html EditListingComponent. <a [routerLink]="['/listings']">Back</a> однако, когда я хочу вернуться к конкретному листингу с использованием следующего кода, он не работает ... <a [routerLink]="['/listing/'+listing.$key]">Back</a> ... код файла edit-list.component.ts находится у меня в вопросе ... можете ли вы объяснить, почему это может быть .. у меня есть доступ к свойству $ key листинга, потому что я вижу это в моем console.log
Показать ещё 1 комментарий
1

Попробуйте добавить this в контексте:

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

Ещё вопросы

Сообщество Overcoder
Наверх
Меню