Ok, here's yet another question about how to get a view to reflect data changes.
I have a service and a related component (page-message) which is hosted in the main app component template.
The service exposes an array. Initial data in the array displays, but any changes to the array are not recognized by the view.
I suspect that it may be required to use rx Observable in order to make this work, but I'm not clear on when that is required.
Edit: Here is a working Plunker demonstrating that Observable is not required: https://plnkr.co/edit/2iK9YOwLFfY3EylJn6At?p=preview
What am I missing to get the page-message component HTML view to recognize and render changes to the messageService.pageErrorMessages array?
app.component.html
<page-message></page-message>
app.component.ts snippet to demonstrate I'm providing the services in the app component
@Component({
moduleId: __moduleName, // fully resolved filename; defined at module load time
selector: 'my-app',
directives: [ROUTER_DIRECTIVES, NavbarComponent, PageMessageComponent],
templateUrl: "app.component.html",
providers: [ApiService, MessageService]
})
export class AppComponent {
...
message.service.ts
I am using message.service to provide an interface to add/remove messages
import {Injectable} from '@angular/core';
@Injectable()
export class MessageService {
constructor() {
}
pageErrorMessages: Array<string> = new Array();
addPageError(message: string) {
this.pageErrorMessages.push(message);
}
}
page-message.component.html
*This is the component HTML that is not updating correctly *
<div *ngFor="#message of messageService.pageErrorMessages">
<div class="alert alert-danger">{{message}}</div>
</div>
page-message.component.ts
import {Component} from '@angular/core';
import {MessageService} from "./../services/message.service";
@Component({
moduleId: __moduleName,
selector: __moduleName,
templateUrl: "page-message.component.html",
providers: []
})
export class PageMessageComponent {
constructor(public messageService: MessageService) { }
}
some-other-component.ts
This is where I add an entry to the messages array
submit() {
this.messageService.addPageError("this is an error");
}
providers: [MessageService]? If so, then that is your problem... you have two instances of your service. Provide the service once, somewhere higher in your component tree.submit()? If the event that triggers that eventually results in callingsubmit()is not monkey-patched by Angular, then change detection won't run, hence your view won't update. (You shouldn't need an Observable to get this to work... NgFor will check each item of the array for changes, each time Angular change detection is executed.)