TypeError: Cannot read property 'back' of undefined

1.1k views Asked by At

This is my component.html

<button type="button"
    (click)="save()">Save</button>

This is my component.ts

private heroService: HeroService;
private location: Location;
constructor(heroService: HeroService) {
    this.heroService = heroService;
}
ngOnInit() { }

@Input("hero") hero: Hero;

public save(): void {
    this.heroService.updateHero(this.hero)
        .subscribe(()=> this.goBack());
}
goBack(): void {
    this.location.back();
}

This is my service.ts

private heroesUrl = 'api/heroes'; 
updateHero(hero: Hero): Observable<any> {
    return this.http.put(this.heroesUrl, hero, httpOptions).pipe(
        tap(_ => this.log(`updated hero id=${hero.id}`)),
        catchError(this.handleError<any>('updateHero'))
    );
}

When i click save in my application i am getting the below error while location.back(); is called.

https://i.stack.imgur.com/S6F3V.png

1

There are 1 answers

3
abdul-wahab On BEST ANSWER

Inject Location in component's constructor as you are doing it with HeroService.

constructor(heroService: HeroService,
            location: Location) {
    this.heroService = heroService;
    this.location = location;
}