Angular Service将变量值传递给app.component

时间:2017-07-06 10:48:28

标签: javascript angular

我有一个服务,其中包含一个名为url的变量。

以下是代码:

//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');
  }

}

这是我想从服务中调用url变量的文件:

// 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);

  }


}

我的问题是......如何将service.ts中的url值传递给app.component.ts?

1 个答案:

答案 0 :(得分:1)

例如,将getter / setter方法添加到DataService

public getUrl(){
    return this.url;
}

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

然后从AppComponent

中调用它们
let url = this.service.getUrl();

检索值,并且:

this.service.setUrl(another_url);

设置它。