简体   繁体   English

数组正在更新,但视图不在Angular 2中

[英]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. 您的蓝牙库可能在Angulars区域之外运行,并且当在Angulars区域之外运行的代码更新模型时,不会调用Angulars更改检测。

There are different strategies to invoke change detection manually. 有多种策略可以手动调用更改检测。 Triggering Angular2 change detection manually 手动触发Angular2更改检测

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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