angularjs - Angular2服务将响应传递给组件

标签 angularjs angular

我正在尝试将 http 请求与我的组件分离并将其放入服务中,如何将从请求中获得的响应传递到组件中的操作?

就像在 Angular 1 中一样,您可以在 Controller 中执行类似以下代码的操作,并在服务中执行 http 请求。

var getGenreList = function() {
            coreGenreService.getGenreList(vm.id)
                .then(function(response) {
                     console.log(vm.name);
                });
        }

我尝试应用相同的逻辑,但我不确定如何将响应传递给我的 Controller 。

服务:

getUser(){
        this.http.get('http://../api/User?email='+this.customerEmail)
            .map(response => response.text())
            .subscribe(data => {
                if (data) {
                    var userObj = JSON.parse(data);
                    this.UserEmail = userObj.EmailAddress;
                }
        });
    }

我可以看到这是获取 json 对象,但是当我进行搜索时,我在对象中没有看到任何值,我猜测是因为它没有在 searchUser() 中传递>

searchUser() {
    this.isLoading = true;
    if(!this._searchService.getUser()){ 
        setTimeout(() => {
            this.isLoading = false;
        }, 500)
    }
}

Html 输入结构:

<input type="text" name="UserEmail" [(ngModel)]="customerEmail" placeholder="Search customer email"> <br>
<button (click)="UserCustomer()" class="omni-btn search-btn float-shadow">Search</button>

最佳答案

您需要这样重构您的服务:

getUser(customerEmail: string): Observable<string>{
    return this.http.get(`http://../api/User?email=${customerEmail}`)
        .map(response => response.json());
}

在您的组件中,您可以像这样调用服务:

searchUser() {
  this.isLoading = true;
  this._searchService.getUser(this.customerEmail)
    .subscribe(user => { 
      this.isLoading = false;

      // To use for data binding in the component
      this.user = user;

      console.log('user = ', user);
  });
}

关于angularjs - Angular2服务将响应传递给组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38914316/

相关文章:

javascript - AngularJS 选择下拉菜单 - 选择默认选项

angular - Electron/Angular 示例应用程序中的“TypeError: window.require is not a function”

angularjs - 如何在 ng-repeat 中显示元素一次

javascript - 使用 Google 地方信息自动填充功能强制街道地址?

javascript - Angular 间隔卡住

javascript - Angular js $http 服务 :- header is not accessible inside catch block

javascript - Angular2 等待 DOM 元素加载

node.js - 需要在 Material 数据表中显示嵌套的 JSON 对象

angular - fa 图标不随 ngClass 变化

Angular 6 : Mat-tree-node selection/click event implementation