【发布时间】:2018-09-10 13:33:12
【问题描述】:
我无法更新我的角度服务变量值。
我有两个不相关的组件,我想使用 service 将更新的对象从一个发送到另一个。但我无法更新服务中的对象。
第一个组件:
import { SoruService } from '../soru.service';
import { SoruModel, SecenekModel } from '../soruModel';
@Component({
selector: 'app-first',
templateUrl: './first.component.html',
styleUrls: ['./first.component.scss'],
providers: [SoruService]
})
export class FirstComponent implements OnInit {
public soruLst : [SoruModel];
constructor( private soruServis : SoruService ) { }
ngOnInit(){
this.soruServis.getirSoruLst().subscribe( veri => {
this.soruLst = veri as [SoruModel];
})
}
//// MAKE SOME CHANGES ON "soruLst" locally
// Send updated 'soruLst' to service
updateSoruLst(){
this.soruServis.updateSoruLst(this.soruLst);
}
}
我的服务:
import { Injectable } from '@angular/core';
import { SoruModel, SecenekModel } from './soruModel';
import { Http } from '@angular/http';
const metaJson = 'assets/data/Meta.json';
@Injectable()
export class SoruService {
public sorular = [] as [SoruModel];
constructor( private http:Http ) {
this.sorular = [] as [SoruModel];
}
getirSoruLst() {
return this.http.get(metaJson)
.map(yanit => yanit.json())
}
updateSoruLst( soruLst : [SoruModel] ) {
this.sorular = soruLst;
}
getSorular() : [SoruModel] {
return this.sorular;
}
}
第二个组件:
mport { SoruService } from '../soru.service';
import { SoruModel, SecenekModel } from '../soruModel';
@Component({
selector: 'app-second',
templateUrl: './second.component.html',
styleUrls: ['./second.component.scss'],
providers: [SoruService]
})
export class SecondComponent implements OnInit {
public soruLst : [SoruModel];
constructor( private soruServis : SoruService ) { }
ngOnInit(){
this.soruLst = this.soruServis.getSorular();
console.log(this.soruLst);
}
}
这就是我想做的:
在 FirstComponent 中,从服务中获取 'soruLst' 并在本地进行更改(成功)
在 FirstComponent 中,将更改后的“soruLst”发送到服务(成功 - updateSoruLst)
-
在服务中,更新“sorular”,在“updateSoruLst”中(失败 - 它没有改变,只是在函数范围内改变,但我仍然无法读取更新的值)。我对此有疑问:
updateSoruLst(soruLst:[SoruModel]){ this.sorular = soruLst; }
"this.sorular" 值不会全局更改。
- 在 SecondComponent 中,从服务中读取更新的“sorular”(失败,仍然无法读取更新的值)
我想我必须改变我的服务,但找不到我必须改变的地方..
如何更新服务中的对象?
【问题讨论】:
-
每个组件在其提供者中都有 SoruService。所以每个都有自己专用的 SoruService 实例。服务应该在 NgModule 中提供,而不是在组件中。阅读文档:angular.io/guide/hierarchical-dependency-injection。当您使用它时,还请阅读有关 Http 的部分,并停止使用已弃用的 Http 服务。然后阅读 RxJS 以及使用服务的组件交互:angular.io/guide/…。
标签: angular variables service updating