I'm trying to build a small application using angular2 with more reusable components. Here, I want to have a Loader Service which gets executed on every xhr call.
For that, this is what I came up with
Using Promise
export class SpinnerService { showSpinner = false; spinnerPromise(observableToWaitFor: Observable<any>, text?: string): Promise<any> { this.showSpinner = true; return promiseToWaitFor.toPromise() .then((data) => { this.showSpinner = false; return data; }); } }
This is how I'm consuming my SpinnerService
constructor(private requestService: RequestService, private spinnerService: SpinnerService) { } signin(username: string, password: string) { let url = _.template(API_Constant.LOGIN)({ username: username }); return this.spinnerService.spinnerPromise(this.requestService .makeRequest(url, RequestMethod.Get)) .then(data => { let peoples = data.results; let found = _.find(peoples, (p: any) => p.name.toLowerCase() === username.toLowerCase()); if (found && found.birth_year === password) { } else { return Promise.reject('Invalid username or password'); } }); } }
It works fine till some extent. But I'm not very well convinced with the usage, as it restrict the AuthService to consume Promise.
Using Observable
I'm a beginner in using Observable, so I don't know how difficult or easy it is to implement a generic Loader Service.
This is what I tried
@Injectable()
export class SpinnerService {
showSpinner = false;
public consumer: ReplaySubject<any> = new ReplaySubject(1);
spinnerPromise(observableToWaitFor: Observable<any>, text?: string) {
this.showSpinner = true;
return observableToWaitFor.subscribe(
response => this.consumer.next(response),
error => { this.showSpinner = false; },
() => { this.showSpinner = false; }
);
}
}
This returns a Subscription. But is there a way to update the showSpinner without subscribing it.