weixin_33691598 2016-05-21 20:33 采纳率: 0%
浏览 6

Angular中的HTTP请求

I'm trying my hand at making api calls with Angular js. Unfortunately, I seem to be having some trouble. I am trying to pass a hero name into a form field and use that information to converse with my backend api. Unfortunately, I'm not getting any response data when I try to make contact. Any tips on how to make a successful call?

Here is the controller.

vm.errorMsg = '';

vm.hero = '';

function getCharacter(hero) {
    $http({
        method: "GET",
        data: {
            format: 'json'
        },
        url: "localhost:8080/character/heroByName/" + hero
    }).then(function mySuccess(response){
        vm.hero = response.data;
        console.log(vm.hero);
    }, function myError(response){
        vm.errorMsg = response.statusText;
        console.log(vm.errorMsg);
    });
}

Here is the form field, where you can enter a hero name.

<div class="container">
  <h2>{{character.title}}</h2>
  <div class="row">
    <div class="col-md-8 col-md-offset-2">
      <div class="input-group">
        <input type="text" class="form-control" placeholder="Wolverine" ng-model="character.hero">
        <span class="input-group-btn">
        <button class="btn btn-default" type="submit" ng-click="character.getCharacter(character.hero)">Go!</button>
        </span>
      </div>
    </div>
  </div>
</div>
  • 写回答

1条回答 默认 最新

  • weixin_33713503 2016-05-21 20:39
    关注

    You should expose your function to the scope by assigning it to vm.getCharacter. Afterwards you can call it in your template via ng-click="vm.getCharacter(character.hero)".

    Controller

    vm.errorMsg = '';
    vm.hero = '';
    vm.getCharacter = getCharacter;
    
    function getCharacter(hero) {
        $http({
            method: "GET",
            data: {
                format: 'json'
            },
            url: "localhost:8080/character/heroByName/" + hero
        }).then(function mySuccess(response){
            vm.hero = response.data;
            console.log(vm.hero);
        }, function myError(response){
            vm.errorMsg = response.statusText;
            console.log(vm.errorMsg);
        });
    }
    

    Template

    <button class="btn btn-default" type="submit" ng-click="vm.getCharacter(character.hero)">Go!</button>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗