如何解决为什么 Angular Service 的共享数据没有在 html 中更新?
我正在使用服务在 02 个不相关的组件“home”和“results”之间共享一个数组。在我的 interaction.service.ts
中,我有以下代码:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class InteractionService {
private _teacherMessageSource = new Subject<any>();
teacherMessage$ = this._teacherMessageSource.asObservable();
constructor() { }
sendMessage(message: any){
this._teacherMessageSource.next(message)
}
}
"message" 是一个浮点数组,但我只是将它设置为 any。当我在“home”组件中收到后端的响应时,我只是将它传递给了 Servic 的 sendMessage() 函数:
this.http.post<any>("http://127.0.0.1:5000/",formData).subscribe(
(response)=> {
console.log(response) // array of floats
this._interationService.sendMessage(response);
},(error)=> console.log(error)
)
然后在结果组件中我得到消息并且我可以在控制台上打印它,但是当我将它影响到另一个数组“selectedMessage”以便在 HTML 中打印它时,它总是显示为空:
public selectedMessage=[];
constructor(public _interactionService: InteractionService,private http: HttpClient) { }
ngOnInit(): void {
this.getSpecialities();
this._interactionService.teacherMessage$
.subscribe(
message => {
alert(message); // message is an array of floats and it shows normally with alert(message)
this.selectedMessage = message;
//console.log(this.selectedMessage);
}
);
}
我的 html 是:
<ul>
<li><strong> SSI </strong>: {{selectedMessage[0]}}</li>
<li> <strong>RSD</strong>:{{selectedMessage[1]}} </li>
<li><strong>IL</strong>: {{selectedMessage[2]}}</li>
<li><strong>MIV</strong>: {{selectedMessage[3]}}</li>
<li><strong>SSI</strong>: {{selectedMessage[4]}}</li>
<li><strong>BIGDATAA</strong>: {{selectedMessage[5]}}</li>
<li><strong>BIOINFO</strong>: {{selectedMessage[6]}} </li>
</ul>
请问可能是什么问题?
解决方法
问题是您的 html 正在呈现同步数据,而在组件中您提供异步数据(即使在 ngOnInit 中)。 简单的解决方法是将 *ngIf 放在您的列表中,并更好地将 selectedMessage 声明为正确的数组,但不要将其分配为空数组:
selectedMessage: selectedMessage[];
<ul *ngIf=selectedMessage>
<li><strong> SSI </strong>: {{selectedMessage[0]}}</li>
<li> <strong>RSD</strong>:{{selectedMessage[1]}} </li>
<li><strong>IL</strong>: {{selectedMessage[2]}}</li>
<li><strong>MIV</strong>: {{selectedMessage[3]}}</li>
<li><strong>SSI</strong>: {{selectedMessage[4]}}</li>
<li><strong>BIGDATAA</strong>: {{selectedMessage[5]}}</li>
<li><strong>BIOINFO</strong>: {{selectedMessage[6]}} </li>
</ul>
,
您正在尝试访问可能不存在的异步数据。直接的解决方案是异步管道。
<ul>
<li *ngFor="let msg of (interactionService.teacherMessage$ | async)">
<strong> Something </strong>: {{msg}}
</li>
</ul>
- 这避免了对空数组的访问
- 链接到 stackblitz 上的示例代码:https://stackblitz.com/edit/angular-12ziph?file=src/app/app.component.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。