arrays - 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!
解决方案
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>();
推荐阅读
- ms-word - Word OpenXml Word 发现不可读的内容
- string - 有没有办法测量一组字符串的相似度?一种“质量”Levenshtein 距离?
- python - 等待一切完成(异步)
- c - 在 Linux 内核编程中进行 CPU SRJF 调度时发生 En/Dequeue 错误
- javascript - 对 axios 响应数据的反应
- oracle - 我可以在 Oracle 12c 中声明本地临时表吗
- python - Pysal:如何使用 pysal 回归模型进行交叉验证?
- javascript - 变量将 DOM 元素处理为 null。为什么会这样?
- javascript - 在 JSON 中打开子对象
- php - AsyncTask 需要永远获取结果