So, I've been pulling my hair out for the last two hours searching for the answer. I have a simple AppComponent like this:
import {Component, OnInit} from '@angular/core';
import {UserDataService} from '../services/user-data.service';
@Component({
selector: 'myapp',
template: `
<h1>Angular 2 app inside a desktop app</h1>
<div *ngIf="data">
{{data}}
</div>
`,
})
export class AppComponent{
public data : Object;
constructor(private userDataService : UserDataService) {}
ngOnInit(){
this.data=this.userDataService.getUserData();
}
}
What I want is to import the data from a configuration file from UserDataService, which looks like this:
import {Injectable} from '@angular/core';
import {Http,Response} from '@angular/http';
import {Observable} from 'rxjs/Rx';
@Injectable()
export class UserDataService{
public data : Object;
constructor(private http : Http){}
getUserData(){
this.http.get('./config.json').map((res:Response)=>res.json())
.subscribe(data => {this.data = data});
return this.data;
}
}
I want to check if a certain variable exists in that config file, and if it does I want to show the div, but the problem is the view does not refresh like I thought it would. I clearly am not grasping the situation so can anyone help me?
Async processing works a bit different.
export class AppComponent {
public data : Object;
constructor(private userDataService : UserDataService) {}
ngOnInit() {
// subscribe and assign result when it arrives to `this.data`
this.userDataService.getUserData().subscribe(data => this.data = data);
}
}
Use .map()
instead of subscribe()
so an Observable
is reaturned instead of a Subscription
to allow the caller to get notified when the data arrives.
Add an actual return
if you want to use the result on call site:
getUserData() {
return this.http.get('./config.json')
.map((res:Response)=>res.json())
// .map(data => {this.data = data});
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments