【问题标题】:why http.post didn't call my controller in angular 2为什么 http.post 没有在 Angular 2 中调用我的控制器
【发布时间】:2016-02-02 10:51:25
【问题描述】:

这是我在 angular2 项目中的服务,我想使用服务中的 create 方法来调用我的控制器。

 create(maillingId: string, name: string, phone: string): Observable<void> {      
    var rp = new RecipientDto(maillingId, name, phone);

    console.log(JSON.stringify(rp));
    console.log(this.apiUrl);
    console.log(this.headers); 

    return this.http.post(this.apiUrl, JSON.stringify(rp), { headers: this.headers })
        .do(null,
        () => {
        })
        .map<any>(response => { });

}

这是我打印出来的 这是我可行的邮递员电话 最后是我的控制器代码

 [HttpPost]
    public IActionResult Post([FromBody]RecipientDto recipientDto)
    {
        MailingList ml = _repository.Get<MailingList>(recipientDto.MaillingId);

        if (ml != null)
        {               
            var rp = new Recipient(Guid.NewGuid());             
            rp.IsActivated = true;
            rp.Name = recipientDto.Name;
            rp.PhoneNumber = recipientDto.Phone;
            ml.Recipients.Add(rp);        
            return Ok();
        }
        return HttpNotFound();          
    }

有一点要提一下,我的前端create方法被调用的时候没有fiddler记录。

delete 的问题相同(也不要调用 api),但 getAll() 是可行的

 getAll(id:string): Observable<Recipient[]> {       

    return this.http.get(`${this.apiUrl+'/'+id}`)
        .map<any>(res => <any>res.json())
        .map(a=> <Recipient[]>a);;

}

和我的 get 控制器

 [HttpGet("{mlId}")]
    public IEnumerable<Recipient> Get(string mlId)
    {         
        List<Recipient> list = _repository.Get<MailingList>(mlId).Recipients;

        return list;
    }

【问题讨论】:

  • 您是否尝试过从您的post 通话中删除.do(null, () =&gt; {})?我不确定你想用它来完成什么。
  • 试过了,还是不行。 fiddler 没有出现任何记录。
  • subscribe 到你的create 方法了吗?我相信 Observables 在订阅之前不会真正触发。
  • 嗨原来你必须订阅 post call 否则它不会调用 api

标签: typescript angular


【解决方案1】:

我在这里有一个工作帖子示例:

var headers = new Headers();
headers.append('Content-Type', 'application/json');
this.http.post('http://some-url/', 
                       JSON.stringify({firstName:'Joe',lastName:'Smith'}),
                       {headers:headers})
.map((res: Response) => res.json())
.subscribe((res:Person) => this.postResponse = res);

看起来您缺少订阅部分。

这里有更多信息: http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http

【讨论】:

  • 感谢您的评论,它现在可以工作了。我以前的版本中没有 map() 和 subscribe()
猜你喜欢
  • 2021-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-12
  • 2014-05-23
相关资源
最近更新 更多