我是Angular
的新用户,我正在实现套接字以从后端获取数据,但现在当我尝试更改模板中通过{{personaName}}
显示的值时,值不会更新?
记录时确实告诉我该值已更改,但在显示时仍未显示数据。
组件:
import { Component, OnInit } from '@angular/core';
import { SocketIoService } from '../../services/socket-io.service'
import { Observable } from 'rxjs/Observable';
import { Subscription } from 'rxjs/Subscription';
import 'rxjs/Rx';
@Component({
selector: 'app-navbar',
inputs: ['personaName'],
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
subscription: Subscription;
personaName: string;
private playerSummary;
constructor(private socket: SocketIoService) { }
ngOnInit() {
this.subscription = this.socket.playerSummary.subscribe((x) => {
console.log(this.personaName);
console.log('Next: %s', x);
if (x != null) {
this.playerSummary = JSON.parse(x);
this.personaName = this.playerSummary["personaname"];
console.log(this.playerSummary);
console.log(this.personaName);
}
},
(err) => {
console.log('Error: %s', err);
},
() => {
console.log('Completed');
})
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
答案 0 :(得分:0)
尝试在模板中使用async
管道,不要订阅组件中的this.socket.playerSummary
observable。尝试将其修改为此,
observedData: Observable<string>; // assuming this.socket.playerSummary returns an observable
this.observedData = this.socket.playerSummary.map((x) => {
if (x != null) {
x = x.json();
return x["personaname"];
}
})
.catch(err) => {
console.log('Error: %s', err);
})
将模板修改为
{{ observedData | async }}
我猜你从中得到了这个想法。您可能必须重构/优化它以使其通过。