最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Call service function from DOM - Angular 2 - Stack Overflow

programmeradmin1浏览0评论

Is there any way to call the function defined in service from a DOM, I can call components function from DOM but how can we call service function, something like this:

@Injectable()
export class UtilsService {
    constructor() {}

    getSessionId() {}
}

<button name="getsession" (click)="UtilsService.getSessionId()">Get Session</button>

Is there any way to call the function defined in service from a DOM, I can call components function from DOM but how can we call service function, something like this:

@Injectable()
export class UtilsService {
    constructor() {}

    getSessionId() {}
}

<button name="getsession" (click)="UtilsService.getSessionId()">Get Session</button>
Share Improve this question asked Sep 30, 2016 at 7:43 Dheeraj AgrawalDheeraj Agrawal 2,35711 gold badges46 silver badges65 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 13

The scope for expressions in view bindings is limited to the the components class instance. There is no support to access statics, globals, types (enums), ... directly from the view.

To be able to refer to it in the view, it has to be accessible via the components class instance:

constructor(public utilsService:UtilsService) {}
<button name="getsession" (click)="utilsService.getSessionId()">Get Session</button>

As usual Gunter answer is perfect, I just wanted say that expose those function on view which are necessary. Don't expose everything from a service on view (Law_of_Demeter).

View

<button name="getsession" (click)="getSessionId()">Get Session</button>

Component Class

export class MyComponent {
    getSessionId: any;
    constructor(private utilsService:UtilsService) {
       this.getSessionId = utilsService.getSessionId;
    }
}
发布评论

评论列表(0)

  1. 暂无评论