简体   繁体   中英

Angular 6 , Send Variable from service to component

I want to pass the result of a function on my service, to my component.

Service:

import { Injectable } from '@angular/core';

@Injectable()
export class passVarHelper {

  header: string;

  constructor() {
    this.header = "Title";
  }


  passindexToHeader(index:string) {
    this.header = index;
    this.takeindexToHeader();
  }

  takeindexToHeader() {
    return this.header;
  }
}

And receive the result on this function in my component:

loadIndex() {
  this.indexSelected = this._passVarHelper.takeindexToHeader();
}

To use a function from a service in Angular you will want to pass that service into your component

// component.ts
constructor( private myService: passVarHelper ){ }

public loadIndex() {
    this.indexSelected = this.myService.takeindexToHeader();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM