我正在尝试将两个Observables组合成一个Observables数组,Angular App可以随着时间的推移订阅并接收值。该方案正在使用聊天机器人。用户提供输入,机器人进行响应,并将两者组合在一个数组中以进行聊天。
请参阅以下内容:
聊天输入组件以获取用户输入:
onNewComment(value: string): void {
this.chatService.addComment(value);
}
然后它与chat.service.ts
import { Injectable, Output } from '@angular/core';
import { Observable, BehaviorSubject, Subject, combineLatest, from, merge, concat } from 'rxjs';
import { environment } from '../../environments/environment';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { UserInput } from '../interfaces/user-input';
import { map, tap, switchMap, mergeMap, toArray, scan, shareReplay, take } from 'rxjs/operators';
import { of } from 'rxjs';
import { text } from '@angular/core/src/render3';
import { Division } from '../interfaces/division';
const headers = new HttpHeaders();
headers.append(
'Content-Type', 'application/json'
);
@Injectable({
providedIn: 'root'
})
export class ChatService {
apiUrl = environment.apiUrl;
conversationSubject: BehaviorSubject<any[]> = new BehaviorSubject<any>([]);
conversationArray$: Observable<any> = this.conversationSubject.asObservable();
private commentAddedSubject = new Subject<any>();
commentAddedAction$ = this.commentAddedSubject.asObservable();
sessionToken$ = this.http.get<any>(`${this.apiUrl}/api/session`).pipe(
map(data => data.session_id),
tap(data => this.addComment('')),
shareReplay(1)
);
commentWithSessionToken$ = combineLatest([
this.sessionToken$,
this.commentAddedAction$
]).pipe(
map(([sessionToken, comment]) => {
return {
session_id: sessionToken,
input: {
text: comment
},
};
}
),
);
botResponse$ = this.commentWithSessionToken$
.pipe(
switchMap(comment =>
of(comment)
.pipe(
mergeMap(data => this.http.post<any>(`${this.apiUrl}/api/message`,
{
userInput: data
},
{
headers: headers
})
),
)
)
);
addComment(newComment?: string) {
this.commentAddedSubject.next(newComment);
}
constructor(
private http: HttpClient,
) { }
}
我尝试了多种方法将commentWithSessionToken$
和botResponse$
组合成一系列用户输入和机器人响应,但没有任何运气。我需要的最终结果是:
[commentWithSessionToken$, botResponse$, commentWithSessionToken$, etc, etc]
任何建议将不胜感激。谢谢。
答案 0 :(得分:0)
请使用rxjs forkJoin
forkJoin(commentWithSessionToken$, botResponse$, commentWithSessionToken$, etc, etc)
返回类型为observable<[commentWithSessionToken$, botResponse$,...]>
答案 1 :(得分:0)
我认为您应该合并您的可观测对象并对其进行扫描
chat$ = merge(this.commentWithSessionToken$, this.botResponse$).pipe(
scan((acc, curr) => ([...acc, curr]), []),
);