无法读取未定义的属性“isXXXXX" [英] Cannot read property 'isXXXXX' of undefined

查看:34
本文介绍了无法读取未定义的属性“isXXXXX"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在我的一个组件上使用共享服务.当我与应用程序根组件一起使用时,它工作正常.当我尝试在另一个模块/仪表板上使用时,出现错误.

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>

</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)

推荐答案

我认为您在您的应用程序中使用了延迟加载,如果是,您必须创建一个共享模块并将您的服务添加到其提供程序中,然后将其导入您想使用的每个模块.

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 {
}

这篇关于无法读取未定义的属性“isXXXXX"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆