0

I am trying to Sync the data from REST API to my UI. but when i fetch the record from Rest API and transforms it,it gives an error of undefined:- I am attaching my code:-

 private datalist: Data[];
  private dataUpdated = new Subject<Data[]>();


  constructor(private http:HttpClient) { 



  }
  getData()
{
  this.http.get<{datalist:any}>("http://myserever/posts")
  .pipe(map((dummydata)=>{
    return dummydata.datalist.map(da=>{
      return {
        Status:da.status
      };
    })

  }))
    .subscribe(data=>{
    this.datalist=data
    console.log("The data is",data);
    this.dataUpdated.next([...this.datalist]);
     })
}

Actual Results:- On pipe Operator it is giving me undefined Error, Here is my Error stack:-

ERROR TypeError: Cannot read property 'map' of undefined
    at MapSubscriber.eval [as project] (get-dummy-data.service.ts:25)
    at MapSubscriber._next (map.js:79)
    at MapSubscriber.Subscriber.next (Subscriber.js:95)
    at MapSubscriber._next (map.js:85)
    at MapSubscriber.Subscriber.next (Subscriber.js:95)
    at FilterSubscriber._next (filter.js:90)
    at FilterSubscriber.Subscriber.next (Subscriber.js:95)
    at MergeMapSubscriber.notifyNext (mergeMap.js:151)
    at InnerSubscriber._next (InnerSubscriber.js:25)
    at InnerSubscriber.Subscriber.next (Subscriber.js:95)

How i can solve the above probelm Thank you

Sam
  • 11
  • 7

1 Answers1

0

First of all you are not using a BehaviorSubject but a Subject (the difference matter, the behavior subject has a value at initialization, the Subject hasn't).

This post resume the difference What is the difference between Subject and BehaviorSubject?

It will depends of your needs to switch for a real behavior subject.

The error, "Cannot read property 'map' of undefined" could be due to your dummydata result that does not contains a datalist property (check casing, spelling ?)

The first map will just take the result of the request (dummydata), then the second will try to iterate on dummydata.datalist property (is it an array, an object?).

So you could check first if the dummydata.datalist property is not undefined, and that it is an iterable thing.

You could modify your code to be like this:

    getData(){
        this.http.get<{datalist:any}>("http://myserever/posts").pipe(
            map(dummydata => dummydata.datalist.map(da => {
                return {
                    Status: da.status
                }
            })),
            // Catch it here
            catchError(error => of([{Status: 'Fail'}]))
        ).subscribe(
            data => {
                this.datalist=data
                console.log("The data is",data);
                this.dataUpdated.next([...this.datalist]);
            },
            // Or catch it here
            err => {
                //Do your error handling
            },
            () => // Do something in any case
        )
    }

Hope this can help you.

Aym_jl
  • 11
  • 2