你好我是角度5的新手,我在appmodule中提供了共享服务,这是服务
import { DetailTransaksi } from '../models/DetailTransaksiModel'
@Injectable()
export class TransaksiService {
UserTrans:Transaksi;
constructor() {
this.UserTrans = new Transaksi();
}
getTransaksi(){
return this.UserTrans;
}
addDetail(data:DetailTransaksi){
this.UserTrans.ListDetail.push(data);
}
countDetail(){
return this.UserTrans.ListDetail.length;
}
}
子组件在router-outlet
之内,然后在子组件中我称为addDetail()
方法,但当我调用countDetail
时,app.component的父组件没有更新,这是我的父组件
import { Component, OnInit } from '@angular/core';
import { TransaksiService } from './services/transaksi.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
numPesanan:number;
constructor(private transService:TransaksiService){
}
ngOnInit(){
this.numPesanan = this.transService.countDetail();
}
}
答案 0 :(得分:0)
问题是,您的ngOnInit()
只会运行一次而代码this.numPesanan = this.transService.countDetail();
只会运行一次。
您可以通过两种方式更新父级。
在您的服务中,创建一个变量:
// private makes it to update only within the service.
private listLength = new Subject<Number>();
// public variable will be used to only observe the changes
listLengthObservable = this.listLength.asObservable();
addDetail(data:DetailTransaksi){
this.UserTrans.ListDetail.push(data);
this.listLength.next(this.countDetail());
}
在父组件中:
this.transService.listLengthObservable.subscribe((updatedLength) => {
this.numPesanan = updatedLength
})