首页 > 代码库 > [Angular 2] Share a Service Across Angular 2 Components and Modules
[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() { }}
[Angular 2] Share a Service Across Angular 2 Components and Modules
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。