[英]Angular2 view not updating after model is set from another component
I have a simple web app that has an app model and a couple of components.我有一个简单的 Web 应用程序,它有一个应用程序模型和几个组件。 When I update an array that I have in my model the view where that model is being consumed does not update.
当我更新模型中的数组时,正在使用该模型的视图不会更新。 When I console log the model array I can see the model being updated just not the view.
当我控制台记录模型数组时,我可以看到模型正在更新,而不是视图。 Any help would be greatly appreciated.
任何帮助将不胜感激。 Below please have a look at what I currently have.
下面请看一下我目前所拥有的。
overview.component.ts概览.component.ts
import { Component, OnInit } from '@angular/core';
import { AppModel } from '../models/app-model';
@Component({
selector: 'app-overview',
templateUrl: './overview.component.html',
providers: [AppModel]
})
export class OverviewComponent implements OnInit {
constructor(public AppModel:AppModel) { }
ngOnInit() {}
}
app-model.ts app-model.ts
export class AppModel {
myArray:Array<any> = [];
constructor(){}
}
overview.component.html (This is the view that is not being updated when the model gets updated)概览.component.html (这是模型更新时未更新的视图)
<td *ngFor="let dataItem of AppModel.myArray">
<span{{ dataItem }}</span>
</td>
This is how I am updating the array in the app model from another component这就是我如何从另一个组件更新应用程序模型中的数组
import { Component, OnInit } from '@angular/core';
import { Http, Response } from '@angular/http';
import { AppService } from '../services/app.service';
import { AppModel } from '../models/app-model';
@Component({
selector: 'other-component',
templateUrl: './other-component.component.html',
providers: [AppService, AppModel]
})
export class OtherComponent implements OnInit {
constructor(private http: Http, public AppService:AppService,public AppModel:AppModel) {}
private updateModel() :void {
this.AppModel.myArray = someArray;
}
ngOnInit() {}
}
For a service you get an instance per provider.对于服务,您会为每个提供者获得一个实例。
If you add a provider to a component, you get as many service instances as you have component instances.如果您向组件添加提供者,您将获得与组件实例一样多的服务实例。 Only the component itself and it's children can inject a provider from a component.
只有组件本身及其子组件才能从组件中注入提供者。
You either need to provide the service on a common parent component or in @NgModule()
.您需要在公共父组件上或在
@NgModule()
提供服务。
With providers only in @NgModule()
you get a single instance for your whole application仅在
@NgModule()
使用提供程序,您将获得整个应用程序的单个实例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.