我的(正常化)状态:
export class State {
chatIDs: string[];
chats: { [chatID:string]: Chat };
}
尝试在某个组件模板中循环聊天(状态为Observable):
<div *ngFor="let chatID of (state$ | async).chatIDs;
let currentChat = (state$ | async).chats[chatID]">
<!---->
</div>
字符串let currentChat = (state$ | async).chats[chatID]
抛出错误:
意外的令牌(,预期的标识符,关键字或字符串
如何获取当前聊天进入循环的引用?例如,作为具有输入(state$ | async).chats[chatID]
的子组件是可能的。但有没有更优雅的方式(没有创建任何新组件)?
Angular v2.4
答案 0 :(得分:0)
您可以先使用*ngIf
指令进行检查,然后使用*ngFor
来重复聊天。
import { Component, OnInit } from '@angular/core';
import { Observable } from "rxjs/Observable";
import { Subscriber } from "rxjs/Subscriber";
export class Chat {
message: string
constructor(message: string) {
this.message = message;
}
}
export class State {
chatIDs: string[];
chats: {
[chatID: string]: Chat
};
}
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
state: any;
ngOnInit(): void {
this.state = new Observable<State>((observer: Subscriber<State>) => {
setInterval(() => {
let state = new State();
state.chatIDs = ['1', '2', '3'];
state.chats = {
'1': new Chat('Chat 1'),
'2': new Chat('Chat 2'),
'3': new Chat('Chate 3')
}
observer.next(state)
}, 1000);
});
}
}
使用* ngIf:
将变量放入范围<div *ngIf="state | async; let s">
<div *ngFor="let id of s?.chatIDs">
{{ s?.chats[id] | json }}
</div>
</div>