加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

角度2的根范围有什么替代方案?

发布时间:2020-12-17 17:26:25 所属栏目:安全 来源:网络整理
导读:我希望子组件访问共享服务获取数据并在将子组件注入主组件之后.我希望sharedservice(rootscope)的数据直接将数据放在mainComponents HTML,like here中. mainComponent.ts import { Component } from '@angular/core';import {ChildComponent} from './child'
我希望子组件访问共享服务获取数据并在将子组件注入主组件之后.我希望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");
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读