Is it a scoping issue or a problem with how my observables are set up? Can you assist me in figuring it out?
To explain my logic: My goal is to first check if the data is available locally before making an http.get request for it. I want to return the local data if it exists, and I thought of returning an observable so that I can subscribe to the function's output whether it returns local or remote data. Any feedback on this approach would be great!
I am using Cory Rylan's blog post (https://coryrylan.com/blog/angular-2-observable-data-services) as a guide to implement my own observable. However, I am facing difficulty in defining my Observer in the getData
function.
You can find Cory's working demo here: Cory's Demo
Here is my non-working demo: My Demo - In the log, you can see that this._dataObserver
in the service is undefined, unlike in Cory's example where it is defined. This is causing issues for me.
Below are snippets from the code:
App.ts
@Component({
selector: 'my-app',
template: `
<landing-page></landing-page>
`,
providers: [DataService],
directives: [LandingPageComponent]
})
export class App {
constructor() { }
}
bootstrap(App, [HTTP_BINDINGS])
.catch(err => console.error(err));
LandingPageComponent.ts
@Component({
selector: 'landing-page',
template : `
hello
`,
})
export class LandingPageComponent implements OnInit{
data : Observable<any[]>;
constructor(
private _dataService : DataService
) { }
ngOnInit() {
this.data = this._dataService.data$;
this._dataService.getData();
}
}
DataService
@Injectable()
export class DataService {
data$ : Observable<any[]>; // data stream
private _baseUrl: string;
private _dataObserver : Observer<any[]>;
private _dataStore : {
data : any[]
};
constructor (
private _http: Http
) {
this._baseUrl = 'http://56e05c3213da80110013eba3.mockapi.io/api';
this.data$ = new Observable(observer => this._todosObserver = observer).share();
this._dataStore = { data: [] };
}
/** **************
* Public functions
*****************/
getData () {
this._http.get(`${this._baseUrl}/todos`)
.map(data => data.json())
.subscribe( data => {
this._dataStore.data = data;
console.log(this._dataObserver); //<------ This is undefined for me!
this._dataObserver.next(this.data);
},
error => {
console.log('couldn\'t load data! ' + error );
});
}
}
Any insights you have would be greatly appreciated.