0

I am still green to Angular, I hope this makes sense. I am working with a third party api in my Ionic/Angular app and trying to fetch the record ID from a JSON array but it grabs the ID of the array index. In my code and screenshot below, I can successfully grab the shipperAddress, loadId objects etc, but not the ID object of the record. I am look for a way to loop through all the records after the index so I can grab the record id.

Edit It just came to me that I had some objects out of order. In my model below, I added a an _ to the first ID field to make it _id which becomes my key then added a second field for ID.

load.model.ts

import {LoadLocation} from './location.model';

export class Load {
    constructor(
        public _id: string,
        public id: string,
        public userId: string,
        public status: string,
        public type: string,
        public totalWeight: string,
        public equipment: string,
        public miles: string,
        public shipperAddress: string,
        public loadId: string,
        public imageUrl: string,
        public pickupDate: string,
        public dropDate: string,
        public delivery: string,
        public notes: string,
        public handler: string,
        public location: LoadLocation
    ) {
    }
}

loads.service.ts

...
fetchLoads() {
    return this.authService.token.pipe(
        take(1),
        switchMap(token => {
            const httpHeaders = new HttpHeaders ({
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + token
            });
            return this.http.post<{ [key: string]: LoadData }>(
                `${this.AUTH_SERVER_ADDRESS}/1.0/quotes`, {'loadId': '6'}, { headers: httpHeaders }
            );
        }),
        map(resData => {
            const loads = [];
            console.log(resData);
            for (const key in resData) {
                if (resData.hasOwnProperty(key)) {
                    loads.push(
                        new Load(
                            key,
                            resData[key]._id,
                            resData[key].userId,
                            resData[key].status,
                            resData[key].type,
                            resData[key].totalWeight,
                            resData[key].equipment,
                            resData[key].miles,
                            resData[key].shipperAddress,
                            resData[key].loadId,
                            resData[key].imageUrl,
                            resData[key].pickupDate,
                            resData[key].dropDate,
                            resData[key].delivery,
                            resData[key].notes,
                            resData[key].handler,
                            resData[key].location
                        )
                    );
                }
            }
            return loads;
            // return [];
        }),
        tap(loads => {
            this._loads.next(loads);
        })
    );
}
...

load.page.html

...
<ion-item *ngFor="let fbload of fbloads">
    <ion-thumbnail slot="start">
        <img src="../../../assets/logo_icon.jpg" alt="">
    </ion-thumbnail>
    <ion-label>
        <h2>Load ID: {{ fbload.loadId }}</h2>
        <p>
            {{ fbload.shipperAddress.address1 }}, 
            {{ fbload.shipperAddress.city }} 
            {{ fbload.shipperAddress.state }} 
            {{ fbload.shipperAddress.zip }}
        </p>
    </ion-label>
    <ion-button
            fill="clear"
            color="primary"
            [routerLink]="['/', 'loads', 'tabs', 'fbloads', 'edit', fbload.id]"
            *ngIf="!fbload.handler">
            View Load
    </ion-button>
</ion-item>
...

console screenshot enter image description here

2 Answers 2

1

Based on what I see in your code and the response of the API call there seems to be an inconsistency.

The response holds the record id in a property called id. However when you try to read the id from the response you're using _id. I suggest you get rid if the underscore and try it again.

UPDATE

A code improvement could be to make use of the .map method provided on an array. This would clean up the code rather nicely. Like so:

httpResponse$.pipe(
  map(response => 
    response.map((item, index) => new Load(...))
  )
)

As the map function returns a new array you don't need to store intermediate results in a variable.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for the feedback.. your answer somehow jogged my memory that I had some fields out of order. See the edit section of my question.
If the problem is resolved. That's what matters ;). I've updated my answer with a little code snippet that could shorten your object creation.
0

The above answer, even though it achieves your result, demonstrates a wrong usage of the map function.

The map method() is used to convert each item of an array and should not be confused with the usage of forEach()

In your case, you are not doing any conversions, instead just looping to create the Load object. This is straight forward using the forEach method, although you need the create an array to push the result. (can also use filter with 1==1 condition if you need array as result)

custom_function(response =>
  response.forEach((item) => new Load(...))
)

The case where you need map is when you need to transform something. See the example below. I need to get details for specific IDs, for which I use filter first, then use map to transform to convert the property names of that IDs. Both filter and map will return an array as result.

var targetID = [1];

var arr = [{
  id: 1,
  name: 'bill'
}, {
  id: 2,
  name: 'ted'
}]

let result = arr.filter(e => {
  return targetID.includes(e.id);
}).map(person => ({
  value: person.id,
  text: person.name
}));

console.log(result);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.