我希望子组件访问共享服务获取数据并在将子组件注入主组件之后.我希望sharedservice(rootscope)的数据直接将数据放在mainComponents
HTML,like here中.
mainComponent.ts
import { Component } from '@angular/core'; import {ChildComponent} from './child'; import {AppServiceService} from './app-service.service'; @Component({ moduleId: module.id,selector: 'rootscope-app',templateUrl: 'rootscope.component.html',styleUrls: ['rootscope.component.css'],directives:[ChildComponent] }) export class RootscopeAppComponent { title = 'rootscope works!'; display:any; constructor(appServiceService:AppServiceService){ this.display=appServiceService.getter(); } }
sharedService.ts
import { Injectable} from '@angular/core'; @Injectable() export class AppServiceService { ser = "hello i am from service"; public data: any; constructor() { } settter(data: any) { this.data = data; } getter() { return this.data; } }
mainComponent的childComponent
import { Component,OnInit } from '@angular/core'; import {AppServiceService} from '../app-service.service' @Component({ moduleId: module.id,selector: 'app-child',templateUrl: 'child.component.html',styleUrls: ['child.component.css'] }) export class ChildComponent implements OnInit { dispaly: string; constructor(appServiceService: AppServiceService) { this.dispaly = "Child component binding..."; appServiceService.settter(this.dispaly); } ngOnInit() {} }
解决方法
$rootScope和$scope都不在Angular2中.您可以考虑使用service(shareService)并将其注入boostrap函数.这样,您就可以在整个应用程序中共享数据(HTML也是如此).
看看这里http://plnkr.co/edit/7A21ofKNdi0uvbMgLUDZ?p=preview
bootstrap(App,[sharedService]);
sharedService
import {Injectable} from 'angular2/core' @Injectable() export class sharedService { name="micronyks"; }
零件
@Component({ selector: 'thecontent',template: ` <h1>Component II - {{ss.name}} </h1> ` }) export class TheContent { constructor(private ss: sharedService) { console.log("content started"); } }