zoukankan      html  css  js  c++  java
  • [Angular 2] Share a Service Across Angular 2 Components and Modules

    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() { }
    
    }
  • 相关阅读:
    山东第一届省赛1001 Phone Number(字典树)
    HD2222 Keywords Search(AC自动机入门题)
    POJ 1947Rebuilding Roads(树形DP + 01背包)
    zoj 3946 Highway Project(最短路 + 优先队列)
    HDU5672String(尺标法)
    HDU5671Matrix(矩阵行列交换)
    HDU5670Machine(抽象进制)
    用户体验评价
    团队冲刺第二阶段-6
    第十四周学习进度
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5889998.html
Copyright © 2011-2022 走看看