angular2服务,实例属性变为undefined

import { Injectable } from '@angular/core';

@Injectable()
export class SpinnerService {

  private _selector = '#spinner';

  show() {
    console.log(this._selector);  // #spinner
    $(this._selector).show();
  }

  hide() {
    console.log(this._selector); // undefined
    $(this._selector).hide();
  }

}

第一次调用的是show函数,第二次调用的是hide函数。这个服务只提供到了根模块的providers中,是在惰性加载模块的组件中调用的函数

阅读 3.3k
2 个回答

惰性加载的模块有自己的子注入器,注入的服务会创造一个新的实例。

这个做法是不可取的,这类似ng1的写法的,推荐的做法如下:

  1. 在你的模板文件(即template.html)中使用结构型指令*ngIf绑定条件变量condition:

    <p *ngIf="condition">
      condition is true and ngIf is true.
      This template will show.
    </p>
    <p *ngIf="!condition">
      condition is false and ngIf is false.
      This template will remove.
    </p>
  2. 在你的component.ts文件里定义如下变量:

    export class yourComponent{
    
        private condition:boolean = true;
        
        //other code
        
    }

    在这里控制变量conditiontrueorfalse即可控制模板的显示和移除。注意,我这里说的是 移除 而不是 隐藏 ,原因你看看这里,这也是一份中文API,请善用。


    希望你能顺利解决问题 :)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题