[英]Angular Service passing variable value to app.component
I have a service which contains a variable called url. 我有一个包含名为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: 这是我要从服务中调用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);
}
}
My question is ... How can I pass the url value from the service.ts to app.component.ts ? 我的问题是...如何将URL值从service.ts传递给app.component.ts?
For instance add getter/setter methods to DataService
: 例如,将getter / setter方法添加到
DataService
:
public getUrl(){
return this.url;
}
public setUrl(url:string){
this.url = url;
return this.url;
}
and then call them like this from AppComponent
: 然后从
AppComponent
这样调用它们:
let url = this.service.getUrl();
to retrieve the value, and: 检索值,并:
this.service.setUrl(another_url);
to set it. 设置它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.