1
votes

I am trying to get values between two dates. In server side its working fine but in front end it's show me error as birthdays.map is not a function

birthday.service.ts

    import {Observable} from 'rxjs/Observable';
    import * as moment from 'moment';
    import 'rxjs/add/operator/map';
    import {HttpClient, HttpParams} from '@angular/common/http';
    import {map} from 'rxjs/operators';

   getbirthdays(start?: moment.Moment, end?: moment.Moment): 
   Observable<birthday[]> {
        let params = new HttpParams();

        if (start) {
          params = params.append('start', start.toISOString());
        }

        if (end) {
          params = params.append('end', end.toISOString());
        }

        return this.http.get('/api/birthday', {params: params}).pipe(
          map(res => res as Object[] || []),
          map(birthdays => birthdays.map(k => new birthday(
            k['_id'],
            new Date(k['datetime']),
            k['gift']))
          )
        );
      }

error in browser console

core.js:1350 ERROR TypeError: birthdays.map is not a function at MapSubscriber.project (birthday.service.ts:28) at MapSubscriber.webpackJsonp.../../../../rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:35) at MapSubscriber.webpackJsonp.../../../../rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54) at MapSubscriber.webpackJsonp.../../../../rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:41) at MapSubscriber.webpackJsonp.../../../../rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54) at MapSubscriber.webpackJsonp.../../../../rxjs/_esm5/internal/operators/map.js.MapSubscriber._next (map.js:41) at MapSubscriber.webpackJsonp.../../../../rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54) at FilterSubscriber.webpackJsonp.../../../../rxjs/_esm5/internal/operators/filter.js.FilterSubscriber._next (filter.js:38) at FilterSubscriber.webpackJsonp.../../../../rxjs/_esm5/internal/Subscriber.js.Subscriber.next (Subscriber.js:54) at MergeMapSubscriber.webpackJsonp.../../../../rxjs/_esm5/internal/operators/mergeMap.js.MergeMapSubscriber.notifyNext

1

1 Answers

3
votes

The Typescript's type checking works for compile-time only and, because it's compiled to JavaScript at the end anyway, all the typings are for developer information only as Typescript has no runtime type check/cast feature

That's why map(res => res as Object[] || []) won't cast the response to Array it'll only tell the IDE what type the response data is (for your information only), it won't modify the data itself (you can define res as Object[], but if the backend sends you the Object, you'll get the same exact object anyway.

If you want to use Array.prototype.map you need to manually parse the response to Array.

You should remove the first map() as it does nothing and set the debugger; in the second to see what data you're getting.