如何解决如何将值从服务存储到 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>
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();
}
}
非常感谢!
解决方法
据我了解你的问题,有几种解决方案可以解决这个问题 但最简单的方法是每次触发初始化方法时创建一个新对象,如下所示
改变这个
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 中班级的顶部
private subject = new Subject<any>();
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。