Angular http请求无法正常工作

Angular http请求无法正常工作,angular,asp.net-core,Angular,Asp.net Core,棱角分明使我发疯 我有两个按钮。 如果单击第一个,我想提出以下请求: 如果我单击第二个,我想提出该请求: 将调用方法“getNextPost()”,该方法似乎有效,但在服务器端不会调用已寻址的方法 以下是我的客户端实现: export class AppComponent implements OnInit { title = 'EventsPresenter'; _hubconnection : signalR.HubConnection; _notification :

棱角分明使我发疯

我有两个按钮。 如果单击第一个,我想提出以下请求:

如果我单击第二个,我想提出该请求:

将调用方法“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)
        {
        }
    }
}
导出类AppComponent实现OnInit{
标题='EventsPresenter';
_hubconnection:signal.hubconnection;
_通知:字符串=“”;
displayedColumns:string[]=['eventDateTime',nbr','element','parent','stateTypeTitle','enumValueTitle','customerObject'];
根目录https://localhost:44373/';
ROOT_API_URL=this.ROOT_URL+'API/';
数据来源:可观察;
数据来源2:可观察;
构造函数(私有http:HttpClient){}
getPosts(){
this.dataSource=this.http.get(this.ROOT\u API\u URL+'events')
}
getNextPost(){
this.dataSource2=this.http.get(this.ROOT\u API\u URL+'events/1')
}
恩戈尼尼特(){
此._hubconnection=new signal.HubConnectionBuilder()
.configureLogging(signar.LogLevel.Trace)
.withUrl('https://localhost:44373/notify') 
.build();
这是一个连接
.start()
。然后(()=>console.log('连接已启动'))
.catch(err=>console.log(“建立连接时出错”);
此._hubconnection.on('BroadcastMessage',(数据:EventData)=>{
控制台日志(数据);
subscribe(v=>v.push(data));
});
}
}
以下是我的服务器实现:

 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)
        {
        }
    }
}
使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用系统线程;
使用System.Threading.Tasks;
使用convisAPI.DataProvider;
使用convisAPI.接口;
使用实体库;
使用Microsoft.AspNetCore.Mvc;
使用Microsoft.AspNetCore.signal;
名称空间convisAPI.Controllers
{
[路由(“api/[控制器]”)]
[ApiController]
公共类事件控制器:ControllerBase
{
//EventDataProvider EventDataProvider;
IEventDataRepository\u eventDataRepository;
IHubContext hubContext;
公共事件控制器(IEventDataRepository eventDataRepository,IHubContext hubContext)
{
_eventDataRepository=eventDataRepository;
_hubContext=hubContext;
}
//获取api/事件
[HttpGet]
公共异步任务Get()
{
return wait_eventDataRepository.GetEvents();
}
//获取api/values/5
[HttpGet(“{id}”)]
公共异步任务Get(int-id)
{
随机r=新随机();
var-ra=r.Next(212,220);
wait_hubContext.Clients.All.SendAsync(“BroadcastMessage”,new EventSummary())
{
Element=“我的元素”+ra,
Details=“Das ist mein Eventgrund”,
EventID=Guid.NewGuid(),
ElementID=Guid.NewGuid(),
EventDateTime=DateTime。现在,
Nbr=ra,
StateNbr=ra,
EnumValueTitle=“Störung”,
StateEnumValue=110+ra
});
返回新的EventSummary();
}
//后api/值
[HttpPost]
公共作废帖子([FromBody]字符串值)
{
}
//将api/values/5放入
[HttpPut(“{id}”)]
公共void Put(int id,[FromBody]字符串值)
{
}
//删除api/values/5
[HttpDelete(“{id}”)]
公共无效删除(int-id)
{
}
}
}
我知道代码“Get(intid)”对您来说可能很奇怪,但我基本上想触发一个信号器通知

有什么想法吗


最好的问候

在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)
}
热烈的问候这里有两个问题

1st: get()方法返回一个可观察的。除非订阅了Observable,否则不会触发/触发它们。 例如:

因此,在您的情况下,不会调用服务器。签入浏览器的网络。如果打了电话,那么它应该显示在那里

第二期:CORS发行。由于对服务器的请求和来自服务器的响应的来源不同,因此可能存在cors问题。在开发阶段,您可以使用浏览器插件来解决这个问题,但它仍然会在生产过程中发生(当您上线时)。要正确解决此问题,需要在服务器端进行一些更改。 在服务器上添加以下内容:

  // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

对于那些在这里登陆但没有任何上述问题的用户,如果您有拦截器的话,请检查您的拦截器。

您的服务器是否位于另一个端口上?Angular在localhost:4200上运行,而asp.net.core在localhost:44373上运行。我不知道您的确切意思。getPosts()中填充数据源的代码工作正常。getNextPost()中以完全相同的方式填充datasource2的代码不起作用。请参见下面的答案。啊,对不起,复制粘贴错误。我会纠正这个错误。谢谢。嗨,简,谢谢你的回答。我还需要将datasource的声明更改为EventData[],而不是ObservaleThank,以获得您的答案。几天前我已经解决了cors问题。你的第一点也是对的。谢谢你,祝你今天愉快!
/* This wont work because it is not subscribed. */
someMethod() {
http.get(someUrl);
}

// this is work since it is subscribed.
someMethod() {
http.get(someUrl).subscribe(res => console.log(res));
}
  // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);