What's an alternative for root scope in angula

2020-04-07 14:17发布

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;
  }
}

childComponent of 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() {}
}

标签: angular
3条回答
▲ chillily
2楼-- · 2020-04-07 15:08

$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).

Look at here. http://plnkr.co/edit/7A21ofKNdi0uvbMgLUDZ?p=preview

bootstrap(App, [sharedService]);

sharedService

import {Injectable} from 'angular2/core'

@Injectable()
export class sharedService {
    name="micronyks";
} 

Component

@Component({
  selector: 'thecontent',
    template: `
    <h1>Component II - {{ss.name}}   </h1>
        `
})
export class TheContent {
  constructor(private ss: sharedService) {
    console.log("content started");
  }
}
查看更多
狗以群分
3楼-- · 2020-04-07 15:10

Given the desired output is that we want to use shared values inside any template, then using a service is not an answer.

The solution is making a base class to all components, where everything we need globally resides.

create a class, name it BaseComponent

export class BaseComponent{

   constructor(){}

   public someMethod(): string{
     return "some string";
   }

   //and whatever methods you need, a method can call services and return data from it

}

and make every component extends it

export class TestPage extends BaseComponent {

and inside its HTML template

<span> {{someMethod()}} </span>

or alternatively if you want a change in the view (template) to be fired from a service function call, you can place a callback in the service and assign it from the component so it will be fired whenever the service function called, take this case as an example

In my case I wanted to show a message that can be fired from any component, so I placed it in the app.component.html which survives along the app lifetime

    <div class="col-lg-12">
        <div [hidden]="!msg" (click)="msg=''" class="alert alert-info" role="alert">
            {{msg}}
        </div>
    </div>

inside the app.component.ts

constructor(private main: MainService){}

msg: string = "";
ngOnInit(): void {
    this.main.showMsg = (msg)=>{this.msg = msg;}
}

the MainService is the service that contains the callback, as you see below

//main.service.ts
public showMsg:(msg: string)=>void;

now from any component, with the main service registered in the constructor, you can show the message as follows

if(this.main.showMsg){
     this.main.showMsg("the message text");
}
查看更多
祖国的老花朵
4楼-- · 2020-04-07 15:14

it is possible by using angular BehaviorSubject and asObservable

Check below example code

Service file

@Injectable()
export class commonService {
    private data = new BehaviorSubject('');
    currentData = this.data.asObservable()

    constructor() { }

    updateMessage(item: any) {
        this.data.next(item);
    }

}

Component

Set the data from any component

 constructor(private _data: commonService) { }
 shareData() {
      this.currentValue = this.queryTerm;
      this._data.updateMessage(this.currentValue);
  }

Listen from any component

constructor(private _data: commonService) { }
ngOnInit() {
        this._data.currentData.subscribe(currentData => this.currentValue = currentData)
    }

You can communicate between any component using this way.

More info and other methodes

查看更多
登录 后发表回答