![](/img/trans.png)
[英]How to store certain values from service response to an array in Angular 6?
[英]How to store values from a service to an array in Angular?
我有一个带有 getter 和 setter 方法的服务,它们从我的对话框组件返回id: number
和title: String
。 我需要将响应中的值存储到我的data
数组中,但我不知道如何。 例如:
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 ",…}
如果你们能帮助我,我将不胜感激。
这是我到目前为止得到的:
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>
共享数据.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();
}
}
非常感谢!
据我了解您的问题,有几种解决方案可以解决此问题,但最简单的方法是每次触发初始化方法时创建一个新的 object,如下所示
改变这个
initialize() {
this.id = this.share.getId();
this.title = this.share.getTitle();
console.log(this.id, this.title);
}
到以下
initialize(): void {
this.id = this.share.getId();
this.title = this.share.getTitle();
const newData = {
id: this.id,
title: this.title
};
this.data.push(newData);
}
您的代码中存在一些语法错误和排序问题,服务和应用程序组件都应该解决(取决于您使用的 angular 版本)。
您还必须在实例方法的实例声明之前声明即时字段,这应该在类/接口的开头
将此移至 share-data.service.ts 中 class 的顶部
private subject = new Subject<any>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.