码迷,mamicode.com
首页 > 其他好文 > 详细

[Angular 2] Share a Service Across Angular 2 Components and Modules

时间:2016-09-20 19:55:42      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:

Services are used to share data between components. They follow a module pattern that allows you to use the data throughout your application so that your data is consistent and in sync.

 

Create a service.module.ts:

import { NgModule} from @angular/core;
import {SimpleService} from ./simple.service;

@NgModule({
})
export class ServicesModule {
    static forRoot(){
        return {
            ngModule: ServicesModule,
            providers: [SimpleService]
        }
    }
}

export {
    SimpleService
}

 

Simple.serivce.ts:

import { Injectable } from @angular/core;

@Injectable()
export class SimpleService {

    message = "Hello";

    constructor() { }

}

 

app.module.ts:

import { NgModule} from "@angular/core";
import {BrowserModule} from "@angular/platform-browser";
import {AppComponent} from ./app.component;
import {HomeModule} from ./components/home/home.module;
import {WidgetsModule} from ./components/widgets/widgets.module;
import {ServicesModule} from ./serivces/service.module;

@NgModule({
    imports:[BrowserModule, HomeModule, WidgetsModule, ServicesModule.forRoot()],
    declarations:[AppComponent],
    bootstrap:[AppComponent]
})
export class AppModule{}

 

Use the SimpleService:

import { Component, OnInit } from @angular/core;
import {SimpleService} from ../../serivces/service.module;

@Component({
    moduleId: module.id,
    selector: home,
    templateUrl: home.component.html
})
export class HomeComponent implements OnInit {

    constructor(private simpleService: SimpleService) {
        console.log("message:", simpleService.message);
    }

    ngOnInit() { }

}

 

[Angular 2] Share a Service Across Angular 2 Components and Modules

标签:

原文地址:http://www.cnblogs.com/Answer1215/p/5889998.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!