简体   繁体   中英

Angular Service passing variable value to app.component

I have a service which contains a variable called url.

Here is the code:

//service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import  'rxjs/add/operator/map';
import  'rxjs/add/operator/do';
import  'rxjs/add/operator/catch';

@Injectable()
export class DataService {

  private url = 'http://someurl.com/';

  constructor (private _http:Http){}

  getDataHttp():Observable<any> {
    return this._http.get(this.url)
      .map((response: Response) => <any> response.json())
      .do(data => console.log('All: ' +  JSON.stringify(data)))
      .catch(this.handleError);
  }

  private handleError(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
  }

}

Here is the file where I want to call the url variable from the service:

// app.component.ts

import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {

  errorMessage;
  data;

  constructor(private service:DataService)  {}

  ngOnInit() {
    this.service.getDataHttp()
      .subscribe(data => this.data = data,
        error => this.errorMessage = <any>error);

  }


}

My question is ... How can I pass the url value from the service.ts to app.component.ts ?

For instance add getter/setter methods to DataService :

public getUrl(){
    return this.url;
}

public setUrl(url:string){
    this.url = url;
    return this.url;
}

and then call them like this from AppComponent :

let url = this.service.getUrl();

to retrieve the value, and:

this.service.setUrl(another_url);

to set it.

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