角度2中根范围的替代方法是什么? [英] What's an alternative for root scope in angular 2?

查看:69
本文介绍了角度2中根范围的替代方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望子组件访问共享服务,并在将子组件注入到主组件之后获取数据.我希望 sharedservice(rootscope)的数据直接将数据放在mainComponents HTML中,

I want the child component to access the shared service take the data and after injecting the child component to main component. I want the data of the sharedservice(rootscope) to directly put the data in 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中均不可用.您可以考虑使用服务(shareService),并将其注入到 boostrap 函数中.这样,您将能够在整个应用程序(以及HTML)中共享数据.

$rootScope and $scope both are not available in Angular2. You can think to use service (shareService) and inject it into boostrap function. This way you will be able to share data throughout application(HTML as well).

看看这里. 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");
  }
}

这篇关于角度2中根范围的替代方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆