angular - 角度 http 请求无法正常工作
问题描述
Angular 让我发疯。
我有两个按钮。如果我点击第一个,我想提出这个请求:
https://localhost:44373/api/events
如果我点击第二个,我想提出这个请求:
https://localhost:44373/api/events/1
将调用方法“getNextPost()”并且它似乎可以工作,但在服务器端将不会调用寻址的方法。
这是我的客户端实现:
export class AppComponent implements OnInit {
title = 'EventsPresenter';
_hubconnection : signalR.HubConnection;
_notification : string = '';
displayedColumns: string[] = ['eventDateTime', 'nbr', 'element', 'parent', 'stateTypeTitle', 'enumValueTitle', 'customerObject'];
ROOT_URL = 'https://localhost:44373/';
ROOT_API_URL = this.ROOT_URL + 'api/';
dataSource: Observable<EventData[]>;
dataSource2: Observable<EventData>;
constructor(private http: HttpClient) {}
getPosts(){
this.dataSource = this.http.get<EventData[]>(this.ROOT_API_URL + 'events')
}
getNextPost(){
this.dataSource2 = this.http.get<EventData>(this.ROOT_API_URL + 'events/1')
}
ngOnInit() {
this._hubconnection = new signalR.HubConnectionBuilder()
.configureLogging(signalR.LogLevel.Trace)
.withUrl('https://localhost:44373/notify')
.build();
this._hubconnection
.start()
.then(() => console.log('Connection Started'))
.catch(err => console.log('Error while establishing connection'));
this._hubconnection.on('BroadcastMessage', (data: EventData) => {
console.log(data);
this.dataSource.subscribe(v => v.push(data));
});
}
}
这是我的服务器实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using convisAPI.DataProvider;
using convisAPI.Interfaces;
using EntityLibrary;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
namespace convisAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class EventsController : ControllerBase
{
//EventDataProvider eventDataProvider;
IEventDataRepository _eventDataRepository;
IHubContext<NotifyHub> _hubContext;
public EventsController(IEventDataRepository eventDataRepository, IHubContext<NotifyHub> hubContext)
{
_eventDataRepository = eventDataRepository;
_hubContext = hubContext;
}
// GET api/events
[HttpGet]
public async Task<ActionResult<IEnumerable<EventSummary>>> Get()
{
return await _eventDataRepository.GetEvents();
}
// GET api/values/5
[HttpGet("{id}")]
public async Task<ActionResult<EventSummary>> Get(int id)
{
Random r = new Random();
var ra = r.Next(212, 220);
await _hubContext.Clients.All.SendAsync("BroadcastMessage", new EventSummary()
{
Element = "Mein Element " + ra,
Details = "Das ist mein Eventgrund",
EventID = Guid.NewGuid(),
ElementID = Guid.NewGuid(),
EventDateTime = DateTime.Now,
Nbr = ra,
StateNbr = ra,
EnumValueTitle = "Störung",
StateEnumValue = 110 + ra
});
return new EventSummary();
}
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
我知道代码“Get(int id)”对你来说可能看起来很奇怪,但我基本上想触发 SignalR 通知。
有任何想法吗?
此致
解决方案
在 Angular 中,每个 HTTP 请求只会在有人收听它们时“触发”。
因此,如果没有人订阅,则不会有任何 http 请求。
getPosts(){
this.http.get<EventData[]>(this.ROOT_API_URL + 'events')
.subscribe(result => this.dataSource = result)
}
getNextPost(){
this.http.get<`EventData>(this.ROOT_API_URL + 'events/1')
.subscribe(result => this.dataSource2 = result)
}
我会写它有点不同,但那是个人风格而不是
getPosts(){
this.dataSource = this.http.get<EventData[]>(this.ROOT_API_URL + 'events')
}
我会写
getPosts():Observable<EventData[]>{
return this.http.get<EventData[]>(this.ROOT_API_URL + 'events')
}
然后我会在需要数据的地方订阅。
...
this.getPosts().subscribe(result => this.isWhereINeedit = result)
温暖的问候
推荐阅读
- python - 如何在 Python 3.x 上通过按键来启动和中断循环
- excel - 范围结束时的值总和由 Cell("address") 定义
- apache-spark - 使用重命名键的 Spark 数据倾斜重新分区
- angular - 从 OnInit Angular 可观察到的 Jasmine 测试订阅服务级别
- javascript - Firebase snapshot.val() 不是函数
- vue.js - 在 v-for 中更改元素背景图像
- c++ - 从巨大的二维结构数组中创建结构的子数组
- javascript - React - 使用 Redux 状态填充第一个选择选项
- database - 如何提取和组合hive数据库中的特定数据表。发现一些错误
- asp.net - Asp.Net.Core 完全自定义