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() { }
    
    }
  • 相关阅读:
    从IL角度彻底理解回调_委托_指针
    微信个人机器人开发
    个人微信接口开发
    淘客微信接口
    python爬虫添加请求头代码实例
    用 Django 开发一个 Python Web API
    Common encryption methods and implementation in Python Python中常用的加密方法及实现
    python aes加密
    # Python语言程序设计基础
    Python语言程序设计基础——4 程序的控制结构
  • 原文地址:https://www.cnblogs.com/Answer1215/p/5889998.html
Copyright © 2011-2022 走看看