简体   繁体   中英

Array being updated but view is not in Angular 2

I have a component that stores an array of servers for display in a list. The component subscribes to an observable from a service.

This is the component code:

import {Client} from '../../connectionService/client.service';


@Component({
    templateUrl: 'build/pages/page1/page1.html',
    providers: [Client]
})
export class Page1 {
    servers : any;

    constructor(private client: Client) {
      this.servers = [];
      this.client._myServers.subscribe((newServer: any) => {
        console.log("new server!", newServer);
        this.servers.push(newServer);
      });
}

The view:

  <ul>
    <li *ngFor='#item of (servers)'>
     Name : {{item.name}}
  </li>
</ul>

The service:

import { Injectable } from '@angular/core';
import {Observable}     from 'rxjs/Observable';
import {Subject}  from 'rxjs/Subject';


    @Injectable()
    export class Client {
      private serversSubject: Subject<any>;
      _myServers : Observable<ServerHandler>;

    constructor() {
        this.serversSubject = new Subject<any>();
        this._myServers = this.serversSubject.asObservable();
    }

...

When I found a server(in the same service as above:

      this.serversSubject.next({"name": result.name, "adress": result.address});

"new server!" gets printed, and the servers is updated in the component, but the view don't show the new items . When I go in and out of the page the new servers appear.

Thanks in advance, Markus

That's a common problem. Your bluetooth library probably runs outside Angulars zone and when code, that runs outside Angulars zone, updates the model, Angulars change detection is not invoked.

There are different strategies to invoke change detection manually. Triggering Angular2 change detection manually

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM