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>
    
    评论

报告相同问题?