javascript - angular2服务,实例属性变为undefined
巴扎黑
巴扎黑 2017-04-11 13:08:19
[JavaScript讨论组]
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中,是在惰性加载模块的组件中调用的函数

巴扎黑
巴扎黑

全部回复(1)
PHP中文网

这个做法是不可取的,这类似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,请善用。


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

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号