Hilal Kaldane
Hilal Kaldane

Reputation: 145

Angular 8 shows TS2339 error, but code works fine and I am getting correct output

I get Error as

ERROR in src/app/home/home.component.ts:13:37 - error TS2339: Property 'name' does not exist on type 'string | Type'. Property 'name' does not exist on type 'string'.

13 this.pageName=route.component.name;

but my code work fine. it only gives me issue while building the code

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.sass']
})
export class HomeComponent implements OnInit {
pageName;
constructor(private route: ActivatedRoute,
private router: Router) { 
  this.pageName=route.component.name;
}
ngOnInit() {
}
}

I tried changing ES version too. doesn't help

Upvotes: 0

Views: 246

Answers (1)

Kenan Güler
Kenan Güler

Reputation: 2013

Apart from what the provided post says, you can use the Route's data property, to feed your components with route-specific custom data.

data:

Additional developer-defined data provided to the component via ActivatedRoute. By default, no additional data is passed.

The developer-defined data is also the safe and practical way, because after the application is created (for production) the class names are given an arbitrary name, so you should not rely on it.

Example:

Routing config

const routes: Routes = [
  // ...
  {
    path: 'home',
    component: HomeComponent,
    data: {
      page: 'Home Page',
      class: 'super-sweet-home',
      color: 'blue',
      // ....
    },
  }
];

Consuming the data

  • Solution 1: Within a component, e.g. HomeComponent.
private subscription: Subscription;

constructor(private route: ActivatedRoute) {}

ngOnInit() {
    this.subscription = this.route.data.subscribe((data: any) => { 
        /* data will be provided after navigation ends successfully */ 
    });
}
public readonly currentPageData = new Subject<any>();

constructor(private router: Router) {
this.router.events.pipe(filter(event => event instanceof ActivationEnd))
  .subscribe(event => {
    this.currentPageData.next((event as ActivationEnd).snapshot.data as any);
  });
}

Within a component, you can then inject the service and subscribe for the currentPageData of the SiteService, e.g.:

constructor(private siteService: SiteService) {
    this.siteService.currentPageData.subscribe((data) => {
      /* data data data */
    });
}

Last but not least: don't forget to unsubscribe the subscriptions.😬

Upvotes: 1

Related Questions