Below is the code snippet in question:
import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions, URLSearchParams } from '@angular/http';
import { Observable } from "rxjs/Observable";
import { Document } from "../api-objects/document";
import { ErrorService } from "../error/error.service";
@Injectable()
export class QuestionsService {
private questionsUrl = '/api/questions'; // URL to web API
headers= new Headers({
'Content-Type': 'application/vnd.api+json',
'Accept': 'application/vnd.api+json' });
public newQnsCount: Observable<number>;
private time:Date;
constructor (
private http: Http,
private errorService:ErrorService
) {
var self = this;
this.newQnsCount = new Observable(
(observable) => {
//configure parameters
let params = new URLSearchParams();
//add filter options to query
params.set("filters", JSON.stringify([{
name: "date",
op: "gt",
val: self.getTime().toISOString()
}]));
//add functions[query] to query
params.set("functions", JSON.stringify([{
name: "count",
field: "id"
}]));
//to prevent returning from cache
params.set("rand", Math.random()+"");
//create options
var options = new RequestOptions({
headers:self.headers,
search: params
});
//create the http observable
var resp = self.http.get(self.questionsUrl, options)
.map(self.extractData)
.catch(self.handleError);
//create an interval that monitors the number of new questions
let interval = setInterval(() => {
resp.subscribe(
//return the count of new questions since the last get time
data => {observable.next(data[0])},
//handle errors
(error) => {
self.errorService.handle401(error);
observable.onError(error);
}
)
});
//return the observable's destroyer function
return () => {clearInterval(interval);}
}
);
}
getTime():Date{
return this.time;
}
addQuestion(question:Document):Observable<Document>{
let body = JSON.stringify(question);
let options = new RequestOptions({headers:this.headers});
var resp = this.http.post(this.questionsUrl, body, options)
.map(this.extractData)
.catch(this.handleError);
resp.subscribe(()=>{}, error => this.errorService.handle401(error));
return resp;
}
getQuestions():Observable<Document>{
let params = new URLSearchParams();
//to prevent returning from cache
params.set("rand", Math.random()+"");
//create options
var options = new RequestOptions({
headers: this.headers,
search: params
});
this.time = new Date();
return this.http.get(this.questionsUrl, options)
.map(this.extractData)
.catch(this.handleError);
}
private extractData(res: Response):Document {
let body = res.json();
return body || { };
}
private handleError (error: any):Observable<Document>{
// 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';
return Observable.throw(error.json());
}
}
I am facing difficulties accessing the scope of the QuestionsService
within the observable creation function. The issue appears to relate to the getTime()
function as it triggers the following error message:
EXCEPTION: Error: Uncaught (in promise): EXCEPTION: Error in :0:0
ORIGINAL EXCEPTION: TypeError: self.time is undefined
...
I attempted using the self
variable to resolve the problem but encountered the same error. Any guidance on resolving this would be highly appreciated.