Cannot read property 'isXXXXX' of undefined [closed]

≡放荡痞女 提交于 2019-12-25 18:48:19

问题


I am trying to use a shared service on one of my components. When I am using with app root component then it is working fine. When I am trying to use on another module/dashboard then I am getting an error.

shared/authorize.service.ts

@Injectable()
export class AuthorizationService {
  isDoingSomething() {
    return "Some Boolean value";
  }
}

dashboard/header/header.component.ts

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent {
 constructor(private _auth: AuthorizeService,
          private _router: Router) { }
}

dashboard/header/header.component.html

<mat-toolbar color="primary" role="heading">
  <div fxFlex fxLayout fxLayoutAlign="flex-end">
    <ul fxLayout fxLayoutGap="10px" class="navigation-items">
      <li routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
        <a routerLink="/home">Home</a>
      </li>
      <li routerLinkActive="active">
        <a *ngIf="_auth.isDoingSomething()" routerLink="/docall">Rest Call</a>
      </li>
    </ul>
  </div>
</mat-toolbar>
**HeaderComponent.html:6 ERROR TypeError:** Cannot read property 'isDoingSomething' of undefined
     at Object.eval [as updateDirectives] (HeaderComponent.html:6)
      at Object.debugUpdateDirectives [as updateDirectives] (core.js:23911)
      at checkAndUpdateView (core.js:23307)

回答1:


I think you are using lazy-loading in your app if it is, you must create a shared module and add your service in its providers, then import it in each module you want to use it.

@NgModule({
  imports: [],
  declarations: [],
  exports:[],
  providers: [
     YourService
  ]
})

 export class SharedModule {
}


来源:https://stackoverflow.com/questions/56089743/cannot-read-property-isxxxxx-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!