C# 来自api的角度和接收流
我正在尝试使用angular 6版本从Web.API接收事件流,因此我的API方法看起来很简单:C# 来自api的角度和接收流,c#,angular,C#,Angular,我正在尝试使用angular 6版本从Web.API接收事件流,因此我的API方法看起来很简单: [HttpGet, ActionName("GetValues")] public async Task GetValues() { try { //Get values from db Response.Headers.Add("Content-Type"
[HttpGet, ActionName("GetValues")]
public async Task GetValues()
{
try
{
//Get values from db
Response.Headers.Add("Content-Type", "text/event-stream");
foreach (var value in values)
{
string jsonResponse = JsonConvert.SerializeObject(value);
byte[] dataItemBytes = Encoding.ASCII.GetBytes(jsonResponse);
await Response.Body.WriteAsync(dataItemBytes,0, dataItemBytes.Length);
await Response.Body.FlushAsync();
}
}
catch (Exception ex)
{
logger.Error(ex);
}
}
所以现在我试着用这样的方法:
return this.httpClient.get<any>(http://localhost/api/System/GetValues`);
返回this.httpClient.get(http://localhost/api/System/GetValues`);
我所得到的只是
在分析的过程中Http失败https://localhost/api/System/GetValues
所以我的想法是,我发送请求并恢复流(流将传输大量数据,这就是我使用它的原因),作为回报,它对swagger和postman都有效。但是我在角度方面有问题,我能做什么?尝试指定
responseType:'text'
this.httpClient.get<any>(http://localhost/api/System/GetValues`,
{ ...options, responseType: 'text' });
this.httpClient.get(http://localhost/api/System/GetValues`,
{…选项,响应类型:'text'});
HttpClient.get()需要一个响应,而这不是您的方法要发送的。在JavaScript-check中,服务器端事件的处理略有不同
通过以下一个简单、漂亮的实现示例(运行NgZone中的所有内容):
import { Injectable, NgZone } from "@angular/core";
import { Observable } from "rxjs";
@Injectable({
providedIn: "root"
})
export class SseService {
constructor(private _zone: NgZone) {}
getServerSentEvent(url: string): Observable<any> {
return Observable.create(observer => {
const eventSource = this.getEventSource(url);
eventSource.onmessage = event => {
this._zone.run(() => {
observer.next(event);
});
};
eventSource.onerror = error => {
this._zone.run(() => {
observer.error(error);
});
};
});
}
private getEventSource(url: string): EventSource {
return new EventSource(url);
}
}
this.sseService
.getServerSentEvent("http://localhost/api/System/GetValues")
.subscribe(data => console.log(data));