Let's say I have a service getting a list of properties:
export class PropertyService {
private properties: any;
constructor(#Inject(Http) http) {
this.http.get('/properties.json')
.map((res:Response) => res.json())
.subscribe(
data => this.properties = data
);
}
getProperty(property: string) {
this.properties[property];
}
}
The problem is that properties is not yet loaded when getProperty is called.
How can I make getProperty to wait for the subscription to populate the array?
I would rather not return a subscription to the components.
EDIT:
I tried paulpdaniels answer and worked with pluck. But I got stuck pretty fast.
So basically I have this PropertyService which returns a HOST.
I have an ApiService that uses that host to do another ajax call to get data.
export class PropertyService {
private properties: any;
constructor(#Inject(Http) http) {
this.properties = http.get('/properties.json')
.map((res:Response) => res.json()).cache(1);
}
getProperty(property: string) {
this.properties.pluck(property);
}
}
export class ApiService {
private http: Http;
private host: string;
constructor(#Inject(Http) http, #Inject(PropertyService) propertyService) {
this.http = http;
this.host = propertyServiceService.getProperty("API.URL"); //Is a subscription
}
getData(): any {
//Here I must subscribe to host, and once available,
//use host to do an ajax call that returns another Observable for the component
}
}
How to realize this?
Short answer is you can't, at least not without introducing some level of asynchronicity to your service.
The simple fact is there is no way to force blocking behavior and wait for the Observable to complete, you should return an Observable which your components should then also know how to consume.
export class PropertyService {
private properties: Observable<any>;
constructor(#Inject(Http) http) {
this.properties = this.http.get('/properties.json')
.map((res:Response) => res.json())
//This will hold onto a cached value of the result
//without re-executing
.cache(1);
}
getProperty(property: string) {
this.properties.pluck(property);
}
}
Edit 1
As Frank Herbert once wrote (paraphrasing) "the stream must flow!". If you need to use nested Observables operators like flatMap allow you to flatten those into a single stream, which you can continue to chain.
export class ApiService {
private http: Http;
private host: Observable<string>;
constructor(#Inject(Http) http, #Inject(PropertyService) propertyService) {
this.http = http;
this.host = propertyServiceService.getProperty("API.URL"); //Is an Observable
}
getData(): Observable<any> {
return this.host.flatMap(url => this.http.get(url), (_, res) => res.json());
}
}
What you can do is to return properties at observable itself and then in destination service start from that properties observable and .flatMap a http request after that. That means introducing more asynchronicity as was mentioned in other answers. Othr solution would be to resolve properties before app / component really start executing by retrieving properties in canActivate router guard. In this case you can be sure that when the component calls method of other service which depends on properties being available synchronosuly the properties were already resolved.
Related
I have the following types:
DataService - Gets data from the server using signalr hub.
AppComponent - which is the entry point for my main application
The data service constructor is as follows.
constructor(private http: Http) {
var hub = $.connection.spwHub;
hub.client.loadEmployees = this.loadEmployees;
$.connection.hub.start().done(() => {
...
});
}
My AppComponent is as follows:
constructor(service: DataService) {
this.company = service.getCompany();
service.getEmployees().then(employees => this.employees = employees);
this.departments = service.getDepartments();
}
I get the following error of course because the hub async call has not returned before the hub connection is made.
EXCEPTION: Error in ./AppComponent class AppComponent_Host - inline template:0:0 caused by: SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.
What is the best way to deal with this issue in AngularJs2?
You can use the APP_INITIALIZER hook to perform logic, get something prepped, whatever, that you need before the rest of the application runs.
In your app.module.ts (or whatever your main module is):
import { APP_INITIALIZER, NgModule } from "#angular/core";
export function init_app(employeeService: EmployeeService) {
return () => employeeService.getEmployees();
}
#NgModule({
<...>
providers: [EmployeeService, {
provide: APP_INITIALIZER,
useFactory: init_app,
deps: [ EmployeeService ],
multi: true
}]
})
export class AppModule { }
The service is returning a Promise which will be automatically handled:
getEmployees() {
return <...function stuff ...>
.toPromise();
}
And here's the github issue where this is documented (no doc on the angular.io site yet): https://github.com/angular/angular/issues/9047
After searching and finding nothing I gave the idea that components that don't need to be loaded should probably be deferred by default. This means that the answer is a no-brainer.
// start.component.ts
constructor() {
// Start the connection
var hub = $.connection.spwHub;
$.connection.hub.start().done(() => {
// This loads the next component and runs the constructor
this.initialized = true;
});
}
// start.component.html
<div *ngIf="initialized">
<main-component></main-component>
<div>
// This type is lazy loaded as soon as the initialized equals true.
// main.component.ts
constructor(employeeService: EmployeeService) {
// Finally, load the needed data.
this.employees = employeeService.getEmployees();
}
I need to inject some HTTP request before each GET. HTTP service requires Observable on return, but before I return it I need to wait on finish of Promise. It looks something like that:
export class HttpInterceptor extends Http {
...
get(url: string, options?: RequestOptionsArgs): Observable<Response> {
somePromise()
.success(() => {
// now I can return Observable object - super.get(url, otpions)
});
}
}
I will be grateful for any solution.
Problem here is that since you override get(url: string, options?: RequestOptionsArgs): Observable<Response> method, you can't call the super one.
One of the solutions would be to create a service wrapping Http and adding your needs, and then use this service as like you are using http.
example:
#Injectable()
export class FooService {
constructor(private http: Http) {
}
public get(url: string, options?: RequestOptionsArgs): Observable<Response> {
somePromise()
.success(() => {
return this.http.get(url, options);
});
}
}
Having this angular2 service taken from official docs with Observable, trying to modify to can pass on fly to the base heroesUrl dynamic parameters like app/heroes/{{country}} and use it like
getHeroes(country) {}
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Hero } from './hero';
import { Observable } from 'rxjs/Observable';
#Injectable()
export class HeroService {
constructor (private http: Http) {}
private heroesUrl = 'app/heroes'; // URL to web API
getHeroes (): Observable<Hero[]> {
return this.http.get(this.heroesUrl)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
How would I do that?
I think you just need to do following things if I understood your point,
getHeroes(country) {}
export class HeroService {
constructor (private http: Http) {}
private heroesUrl = 'app/heroes'; // URL to web API
getHeroes (country): Observable<Hero[]> { //<-----added parameter
return this.http.get(this.heroesUrl + '/' + country) //<-----changed
.map(this.extractData)
.catch(this.handleError);
}
...
...
}
There are lots of resources out there already but I haven't been able to find one that works for one reason or another. Take a generic example: I want to get the response from http://swapi.co/api/people, which will be a list of people from Star Wars.
import {Injectable } from '#angular/core';
import {Http, Response} from '#angular/http';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
#Injectable()
export class OombaDataService {
constructor(private http: Http) {}
private usersUrl = 'http://swapi.co/api/people/';
getData() {
return this.http.get(this.usersUrl)
.map(this.extractData)
}
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
}
A lot of this should be correct since it's based on Angular's own tutorial on the matter. But for whatever reason, when I call it in my components, it just returns an observable object without the JSON data. What am I missing?
At this method:
private extractData(res: Response) {
let body = res.json();
return body.data || { };
}
At the first line, you parse the result of the API call as JSON into a JavaScript object.
Then you return the property data of that object, if it exists. If it doesn't exist, you return an empty object ({ }).
The thing is that the API at http://swapi.co/api/people/ does not bring a response that contains a data property, which means that the extractData() method is always returning an observable of an empty object ({ }).
Besides that, the getData() really returns an Observable, so to get its value, you must subscribe to it, such as:
#Component({
...
providers: [OombaDataService]
})
export class SomeComponent {
constructor(oombaDataService: OombaDataService) {
oombaDataService.getData().subscribe(
x => {
console.log("VALUE RECEIVED: ",x);
},
x => {
console.log("ERROR: ",x);
},
() => {
console.log("Completed");
}
);
}
}
And, since, as said, that API's response does not have any .data property in it, the extractData() should really be (at least until you figure out what you want):
private extractData(res: Response) {
return res.json();
}
That should get things working. Here's a working plunker.
I have created a service that makes a simple GET request:
private accountObservable = null;
constructor(private _http: Http) {
}
getAccount () {
// If we have account cached, use it instead
if (this.accountObservable === null) {
this.accountObservable = this._http.get('http://localhost/api/account')
.map(res => <Account> res.json().data)
.catch(this.handleError);
}
return this.accountObservable;
}
I have added that service in my bootstrap function to provide it globally (my hope is to provide the same instance to all components):
provide(AccountService, { useClass: AccountService })
The problem is when I call this service in different components, a GET request is made every time. So if I add it to 3 components, 3 GET requests will be made even though I check if an observable already exist.
ngOnInit() {
this._accountService.getAccount().subscribe(
account => this.account = account,
error => this.errorMessage = <any>error
);
}
How can I prevent the GET request to be made multiple times?
Use Observable.share():
if (this.accountObservable === null) {
this.accountObservable = this._http.get('./data/data.json')
.share()
.map(res => res.json())
.catch(this.handleError);
}
Plunker
In the Plunker, AppComponent and Component2 both call getAccount().subscribe() twice.
With share(), the Chrome Developer tools Network tab shows one HTTP request for data.json. With share() commented out, there are 4 requests.
There are two types of observables.
Cold Observable : each subscriber receive all the events ( from the begining )
Hot observable : each subscriber receive the events that are emited after subscription.
Cold Observables are the default one. That's what the WS calling is triggered many times.
To make an Observable Hot you have to use following Rx's operators chain :
.publish().refCount()
In your case :
getAccount () {
let accountObservable = this._http.get('http://localhost/api/account')
.map(res => <Account> res.json().data)
.catch(this.handleError);
return accountObservable.publish().refCount();
}
In my case it was because of form post and button clik was set to same listener
The updated solution is:
1) Change your getAccount() method to use share:
getAccount () {
// If we have account cached, use it instead
if (this.accountObservable === null) {
this.accountObservable = this._http.get('http://localhost/api/account')
.pipe(share())
.map(res => <Account> res.json().data)
.catch(this.handleError);
}
return this.accountObservable;
}
2) Add import { share } from 'rxjs/operators'; to the top of your .ts file to get rid of the error on share.