首页 > 解决方案 > How to store values from a service to an array in Angular?

问题描述

I have a service with getter and setter methods, they return me id: number and title: String from my dialog component. I need to store the values from the response to my data array, but I just cant figure out how. For example:


    0: {id: 0, title: "UK ",…}
    1: {id: 1, title: "Usd ",…}
    2: {id: 2, title: "ff ",…}
    3: {id: 3, title: "yy ",…}
    4: {id: 4, title: "nn ",…}
    5: {id: 5, title: "mh ",…}
    6: {id: 6, title: "tr ",…}
    7: {id: 7, title: "es ",…}

I would be so grateful if you guys can help me out.

Here is what I got so far:

app.component.ts

export class AppComponent {
  clickEventsubscription: Subscription

  ngOnInit() {
  }

  id: number;
  title: String;
  data: any = [];

  constructor(private share: ShareDataService) {
    this.clickEventsubscription = this.share.getClickEvent().subscribe(() => {
      this.initialize();
    })
  }

  initialize() {
    this.id = this.share.getId();
    this.title = this.share.getTitle();
    console.log(this.id, this.title);
  }
}

app.component.html

<app-dialog></app-dialog>
<h2>Add values of my service into array:</h2>
<button (click)="initialize()"></button>

share-data.service.ts

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ShareDataService {

  title: String;
  id: number;

  getId() {
    return this.id
  }

  getTitle() {
    return this.title;
  }

  private subject = new Subject<any>();

  sendClickEvent() {
    this.subject.next();
  }

  getClickEvent(): Observable<any> {
    return this.subject.asObservable();
  }

}

Many thanks!

标签: arraysangulartypescriptserviceresponse

解决方案


As far as I understand your question, there are several solutions to solve this but the simplest way is to create an new object every time you trigger the initialize method which goes as follows

change this

initialize() {

    this.id = this.share.getId();
    this.title = this.share.getTitle();
    console.log(this.id, this.title);

 }

to the following

initialize(): void {

    this.id = this.share.getId();
    this.title = this.share.getTitle();

    const newData = {
      id: this.id,
      title: this.title
    };

    this.data.push(newData);
 }

There are some syntax errors and ordering issue in your code both the service and app component which should be solved (depends on what version of angular you are using).

Also you have to declare instant fields before instance declaration of instance method, this should come at the beginning of the class/interface

move this to the top of your class in share-data.service.ts

private subject = new Subject<any>();

推荐阅读