问题
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