我正在创建一个聊天应用程序。我有一个小问题,ngFor
似乎不适合我。
我有2个组件,其中1个是供稿,其中包含另一个组件,即消息。因此feed会显示消息组件列表。
进料 .ts
import { Component, OnInit, OnChanges } from '@angular/core';
import { Observable } from 'rxjs';
import { Message } from '../models/message';
import { MessageService } from '../core/message.service';
@Component({
selector: 'app-feed',
templateUrl: './feed.component.html',
styleUrls: ['./feed.component.css']
})
export class FeedComponent implements OnInit, OnChanges {
feed: Observable<Message[]>;
constructor(private msgService: MessageService) { }
getMessages(): Observable<Message[]> {
return this.msgService.getAllMessages();
}
ngOnInit() {
this.feed = this.getMessages();
}
ngOnChanges() {
this.feed = this.getMessages();
}
}
Feed .html
<div class="feed">
<div *ngIf="feed | async; then fetched else fetching">
</div>
<ng-template #fetched>
<div *ngFor="let message of feed$ | async" class="message">
<app-message [message]=message></app-message>
</div>
</ng-template>
<ng-template #fetching>
<h3>Loading...</h3>
</ng-template>
</div>
消息.ts
import { Component, OnInit, Input } from '@angular/core';
import { Message } from '../models/message';
@Component({
selector: 'app-message',
templateUrl: './message.component.html',
styleUrls: ['./message.component.css']
})
export class MessageComponent implements OnInit {
@Input() message: Message;
sender: string;
body: string;
createdAt: string;
constructor() { }
ngOnInit(message = this.message) {
this.sender = message.Sender;
this.body = message.Body;
this.createdAt = message.CreatedAt;
}
}
消息.html
<div class="messageContainer">
<div class="messageData">
<span class="sender">
<p>{{sender}}</p>
</span>
<span class="createdAt">
<p>{{createdAt | date:'medium'}}</p>
</span>
</div>
<div class="messageContent">
{{body}}
</div>
</div>
这也是我的服务,该服务从asp.net项目执行API调用。
MessageService .ts
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';
import { Message } from '../models/message';
@Injectable({
providedIn: 'root'
})
export class MessageService {
private readonly baseUrl = 'http://localhost:50169';
constructor(private http: HttpClient) { }
getAllMessages(): Observable<Message[]> {
return this.http.get<Message[]>(`${this.baseUrl}/api/messages`);
}
}
我尝试检查API调用的值,并且它具有基于控制台日志的值。
我的问题是Feed组件的ngFor
上没有显示任何数据。
答案 0 :(得分:1)
feed$
的变量,但组件中的字段名为feed
。feed
中分配ngInit
,这意味着如果您对它进行如实检查,它也会求值为true
。因此,无需检查其值,因为一旦模板渲染,它将始终评估为true
。固定的feed.component.html
模板:
<div class="feed">
<div *ngFor="let message of feed | async" class="message">
<app-message [message]="message"></app-message>
</div>
</div>