有我的(规范化)状态:
export class State {
chatIDs: string[];
chats: { [chatID:string]: Chat };
}
尝试在某些组件模板中循环聊天(状态为“可观察”):
<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]
的子组件。但是有没有更优雅的方法(无需创建任何新组件)?角v2.4
最佳答案
您可以使用*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将变量s放入范围内:
<div *ngIf="state | async; let s">
<div *ngFor="let id of s?.chatIDs">
{{ s?.chats[id] | json }}
</div>
</div>
关于javascript - 我可以使用异步管道将变量导入ngFor吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45796271/