我正在尝试将 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/