klp klp - 3 months ago 22
TypeScript Question

How to subscribe to a component variable in angular2

I ma using the header for my server url and i declared it in one of the component and i want to use that header in all components where ever i had a server call but i failed to subscribe to that header,can anyone please help me

my interface component,

import { Injectable } from '@angular/core';
@Injectable()
export class Config {

header = 'http://localhost/a2server/index.php/';

}


my main.ts(here i want to use the header)

var data :any;
constructor(public location: Location,public config:Config,public router: Router, public http: Http, fbld: FormBuilder,public toastr: ToastsManager) {

this.config
.subscribe(header => this.data = data);
console.log(this.data)


i know that i am wrong ,can someone please help me

injectable,

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import {Component} from '@angular/core';
import { IDetails } from './details';
import { Config } from '../headers';
@Component({
providers: [Config]
})
@Injectable()
export class GetCustInfo {
header:any;
str = localStorage.getItem('social');
loc = JSON.parse(this.str);
id = this.loc.profile_id;
constructor(private _http: Http,public config:Config) { this.header = this.config.header;}
private _productUrl = this.header+'profile/editcustominfo/'+this.id;
getCustList(): Observable<IDetails[]> {
return this._http.get(this._productUrl)

.map((response: Response) => {

return <IDetails[]> response.json().data[0];

});

}


}

Answer

You subscribe to observables. For a simple string you just access the property:

var data :any;
  constructor(public location: Location,public config:Config,public router: Router, public http: Http, fbld: FormBuilder,public toastr: ToastsManager) {

    console.log(this.config.header);
Comments