Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

[Feature Request] - New function > push: To add arrays to an existing object#407

Answeredbycyrilletuzi
SvenBudak asked this question inQ&A
Discussion options

Hi! First of all I want to thank you for sharing this great library with us! :)

I always had problems with pushing more arrays into an existing object. Are you planning to implement a new function for this?

You must be logged in to vote

.push() may seem natural in JavaScript, but in fact it is quite unusual in programming languages.

This lib is structured as aMap, and you can see onMDN, there is no.push() method in such data structures. When you want to modify a value, you need to set the whole new value.

So in the case of an array, there are 3 steps:

  1. get the current array (but note that usually you will/should already have this data somewhere in your code),
  2. push a new value into it,
  3. store the whole modified array in the Map.

So you need something like that:

@Injectable({providedIn:'root'})exportclassProductsService{products:string[]=[];constructor(privatestorage:StorageMap,){this.

Replies: 7 comments

Comment options

Hi, thanks for the love. 👍

pushing more arrays into an existing object

You mean adding newvalues to an existingarray, right?

You must be logged in to vote
0 replies
Comment options

Hmm. I always thought that was called an object.)

Unfortunately I am not a good coder. I am actually a frontend designer :) Since a few hours I'm trying to add more arrays

I mean, I have something like this in storage at first:

IndexedDB = [    {        "id": 1,        "name": "Test",    }]

And I'd like to turn it into this:

IndexedDB = [    {        "id": 1,        "name": "Test",    },    {        "id": 2,        "name": "Test",    }]

Up to four items.

I also do not understand why I cannot iterate through vehicles:

this.dataSubscription = this.storage.watch('compareVehicles').subscribe((result: CarInterface) => {    this.vehicles = result;});

I know that this is an issue board and not a stackoverflow ;) But is what I have in mind easily possible only with your service?

You must be logged in to vote
0 replies
Comment options

.push() may seem natural in JavaScript, but in fact it is quite unusual in programming languages.

This lib is structured as aMap, and you can see onMDN, there is no.push() method in such data structures. When you want to modify a value, you need to set the whole new value.

So in the case of an array, there are 3 steps:

  1. get the current array (but note that usually you will/should already have this data somewhere in your code),
  2. push a new value into it,
  3. store the whole modified array in the Map.

So you need something like that:

@Injectable({providedIn:'root'})exportclassProductsService{products:string[]=[];constructor(privatestorage:StorageMap,){this.storage.get('products',{type:'array',items:{type:'string',},}).pipe(/* Following operators are optional, they are here to be sure to have a default value */catchError(()=>of([])),map((products)=>products??[]),).subscribe((products)=>{this.products=products;});}add(product:string):void{this.products.push(product);this.storage.set('products',this.products).subscribe();}}

For your second question,.watch() is not here to iterate over the value when the value is an array..watch() is to listen when the value changed.

If your value is an array, just iterate normally over it:

this.storage.get('products',{type:'array',items:{type:'string',},}).pipe(/* Following operators are optional, they are here to be sure to have a default value */catchError(()=>of([])),map((products)=>products??[]),).subscribe((products)=>{for(constproductofproducts){}});
You must be logged in to vote
0 replies
Answer selected bycyrilletuzi
Comment options

Oh that helped me alot! Thank you! But i really need the watch function ;)
I need to update the list in realtime. So its not possible to iterate on a.watch() list?

And isnt it possible to use an angular interface for the schema? because everytime i change some on the data structure i also need to change it in the schemas to.

You must be logged in to vote
0 replies
Comment options

You can do thefor ... of inside the.watch() callback too.

You must be logged in to vote
0 replies
Comment options

Thank you! I have tried many things, but I guess I just don't have enough basic knowledge in JavaScript. 😅

export interface CarInterface {    id: number;    manufacturer: string;    model: string;    trim_level: string;    year: number;    price: number;    mileage: number;    fuelType: string;    gearboxes: string;    images: string[];}export class VehicleCompareComponent implements OnInit, OnDestroy {    public vehicles: CarInterface;    private dataSubscription: Subscription;    constructor(private storage: StorageMap) {    }    // Any way to delete by index (remove maybe item [3] for example)    deleteVehicle(key, index) {        this.storage.delete(key).subscribe(() => {});    }    ngOnInit(): void {        this.dataSubscription = this.storage.watch('compareVehicles').subscribe((result: CarInterface) => {            this.vehicles = result;        });    }    ngOnDestroy() {        this.dataSubscription.unsubscribe();    }}

HTML

<ul>    <ng-template [ngIf]="vehicles" [ngIfElse]="loading">        <li *ngFor="let vehicle of vehicles; index as index">            <img [src]="vehicles.images[0]" alt="">            <h2>{{vehicles.manufacturer}} {{vehicles.model}}</h2>            <button mat-icon-button (click)="deleteVehicle('products', index)">Delete</button>        </li>    </ng-template>    <ng-template #loading>        <li>            <div>                <mat-spinner diameter="32"></mat-spinner>            </div>        </li>    </ng-template></ul>

This results in endless loop for me...

You must be logged in to vote
0 replies
Comment options

From where doesindex come from in your template?

Yourdelete method must follow the same logic as theadd one: delete the index you want in the class property, then store the whole updated array in local storage.

You must be logged in to vote
0 replies
Sign up for freeto join this conversation on GitHub. Already have an account?Sign in to comment
Category
Q&A
Labels
None yet
2 participants
@SvenBudak@cyrilletuzi
Converted from issue

This discussion was converted from issue #407 on December 08, 2020 21:18.


[8]ページ先頭

©2009-2025 Movatter.jp