我希望子组件访问共享服务并获取数据,然后将子组件注入(inject)到主组件中。我希望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;
}
}
childComponent是mainComponent
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中均不可用。您可以考虑使用服务(shareService),并将其注入(inject) 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");
}
}
关于angular - Angular 2中根范围的替代方法是什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37627197/