0
votes

In my Angular 2 app I am using an observable in my service layer, and then subscribing to that observable in the component layer. My initial set up was working, but now I'm trying to adjust my syntax to match the universal api.service function signature params we're using throughout the app. So far I've been unable to get it work with the new signature/syntax.

First off, this is what I had (that IS WORKING):

getByFilter(page, pagesize, body) {
    const headers = new Headers({ 'Content-Type': 'application/json' });
    const options = new RequestOptions({ headers: this.headers });
    return this.http.post
    (`${this.url}${this.ver}/clients/search/custom?apikey=${this.key}&page=${page}&pagesize=${pagesize}`,
    body, options)
        .map((res: Response) => res.json())
        .catch(this.filterErrorHandler);
}
    filterErrorHandler(error: Response) {
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
}

And what I'm trying (in order to match the call signature from our universal api.service) that's not working is this:

getByFilter(page, pagesize, body) {
    const headers = new Headers({ 'Content-Type': 'application/json' });
    const options = new RequestOptions({ headers: this.headers });
    return this.api.post({
        req: 'clients/search/custom',
        callback: (results) => {
            if (!results.ok) {
                console.error(results);
                return Observable.throw(results.data.json().error || 'Server error');
            }
            console.error(results);
            return Observable.from(results.data.json());
        }
    });
}

The specific error message I'm getting is:

Property 'subscribe' does not exist on type 'void'.

I thought this is the kind of error message you get if you're forgetting to return in the api call. But I am returning, so I'm not clear on what I'm doing wrong here.

Also, to add, I have the api service being injected in my constructor, like so:

constructor(private http: Http, private api: API) {}

And the post call in our API service has a call signature that looks like this:

public post(params: {
    req: string,
    reqArgs?: any,
    reqBody?: any,
    callback?: IRequestCallback
})
{
    params['reqType'] = 'post';

    this.runHttpRequest(params);
}

/**
 * Internal method used within the service to perform
 * an HTTP request to the API
 *
 * @param params
 */
private runHttpRequest(params: {
    req?: string,
    reqArgs?: any,
    reqBody?: any,
    callback?: IRequestCallback,
    reqType?: string
})
{
    let {req, reqArgs, callback, reqBody, reqType} = params;

    // Check request string
    if (String.isNullOrEmpty(req)) throw 'Undefined request';

    // Initialize options if undefined
    if (!reqArgs) reqArgs = {};

    // Build URL
    let route = this.buildRequestUrl(req, reqArgs);

    if (this.http[reqType] === undefined) throw 'Cannot process HTTP request, undefined request type';

    // Call HTTP
    this.http[reqType](route, reqBody)
        .map(function (res: Response)
        {
            let r: IResponse =
                {
                    ok: res.ok,
                    status: res.status,
                    statusText: res.statusText
                };

            let body = null;

            try
            {
                body = res.json();
            }
            catch (err)
            {

            }

            r.data = body || res;

            // Content cleanup; If a data property is provided within the
            // body of the response, then we use that
            // information as the data requested.
            if ('data' in r.data)
            {
                Object.assign(r, r.data);
            }

            return r;
        })
        .catch(function (error: any)
        {
            let errMsg = (error.message) ? error.message :
                error.status ? `${error.status} - ${error.statusText}` : 'Server error';

            if (callback) callback(error);

            return Promise.reject(errMsg);
        })
        .subscribe(function (args: any)
        {
            if (callback) callback(<IResponse> args);
        });
}

And here's an example of where I'm subscribing in the component (this is where the error is arising):

ngOnInit() {
    this.clientService.getByFilter(this.page, this.pagesize, {
            })
            .subscribe(resRecordsData => {
                this.records = resRecordsData;
                console.log(this.records);
            },
            responseRecordsError => this.errorMsg = responseRecordsError);
}
1
where are you subscribing it and you in which line are getting this error - Aravind
Added that above. - Muirik

1 Answers

1
votes

You are returning the return value of the api.post method:

return this.api.post()

This method is not returning an Observable. Actually, it does not look like it is returning anything at all:

public post(params: {
    req: string,
    reqArgs?: any,
    reqBody?: any,
    callback?: IRequestCallback
})
{
    params['reqType'] = 'post';

    this.runHttpRequest(params);
}

That is why you are receiving the error you see. How are the other parts of the app that are using this API handling this?