admin管理员组文章数量:1426033
I am calling an api endpoint in angular 5 using Http import to populate a select dropdown but I am getting undefined when i log it to the console and the dropdown does not populate with any data...its meant to be item categorys.
item-category.ts
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import {Router} from '@angular/router';
import { Globals } from '../shared/api';
import { of } from 'rxjs/observable/of';
import 'rxjs/add/operator/toPromise';
declare var $: any;
@Injectable()
export class ItemCategoryService{
private categoryUrl = this.globals.CATEGORYS_URL;
constructor(private http: Http, private globals: Globals, private router:Router) { }
fetchCategories(){
let v = this.page_header();
return this.http.get(this.categoryURL, v)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
};
}
itemCategoryponent.ts
fetchCategorys(){
this.categorySrv.fetchCategories().then(response =>this.categorys = response.results )
.catch(error=> this.error = error )
console.log(this.categorys); // <== undefined
}
itemCategoryponent.html
<select class="form-control" [(ngModel)]="product.category"[formControl]="productForm.controls['productCategory']" require>
<option *ngFor="let item of categorys" [value]="item.slug">{{item.name}}</option>
</select>
This is what I have but undefined is what i get in the console and the dropdown has nothing from the api, inspecting shows nothing also...what could I have gotten wrong?
I am calling an api endpoint in angular 5 using Http import to populate a select dropdown but I am getting undefined when i log it to the console and the dropdown does not populate with any data...its meant to be item categorys.
item-category.ts
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions } from '@angular/http';
import {Router} from '@angular/router';
import { Globals } from '../shared/api';
import { of } from 'rxjs/observable/of';
import 'rxjs/add/operator/toPromise';
declare var $: any;
@Injectable()
export class ItemCategoryService{
private categoryUrl = this.globals.CATEGORYS_URL;
constructor(private http: Http, private globals: Globals, private router:Router) { }
fetchCategories(){
let v = this.page_header();
return this.http.get(this.categoryURL, v)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
};
}
itemCategory.ponent.ts
fetchCategorys(){
this.categorySrv.fetchCategories().then(response =>this.categorys = response.results )
.catch(error=> this.error = error )
console.log(this.categorys); // <== undefined
}
itemCategory.ponent.html
<select class="form-control" [(ngModel)]="product.category"[formControl]="productForm.controls['productCategory']" require>
<option *ngFor="let item of categorys" [value]="item.slug">{{item.name}}</option>
</select>
This is what I have but undefined is what i get in the console and the dropdown has nothing from the api, inspecting shows nothing also...what could I have gotten wrong?
Share Improve this question asked May 3, 2018 at 17:41 CE0CE0 1913 gold badges7 silver badges18 bronze badges 1-
That's because you are already consuming the Promise in
fetchCategories()
ofietm-category.ts
– Ashish Ranjan Commented May 3, 2018 at 17:49
2 Answers
Reset to default 1That's because you're logging this.categorys
before the response is returned.
try with
fetchCategorys(){
this.categorySrv.fetchCategories().then((response: any) => {
this.categorys = response.results;
console.log(this.categorys); // Log here instead of outside the promise
})
.catch(error=> this.error = error )
// Remove this console.log()
console.log(this.categorys); // <== It is correct to be undefined here because it is not in the success promise
}
Also, you need to remove the .then() and .catch() handler inside the service's fetchCategories()
function. It should just be -
fetchCategories(){
let v = this.page_header();
return this.http.get(this.categoryURL, v)
.map(response => response.json())
.toPromise();
}
No need to consume the promise in the service
There is no benefit in changing your observable to a promise
Keep the service returning an observable:
//service
fetchCategories(){
let v = this.page_header();
return this.http.get(this.categoryURL, v)
.map(response => response.json())
}
and in your ponent, consume it as an observable
this.categorySrv.fetchCategories().subscribe( (response: any) => {
this.categorys = response.results;
console.log(this.categorys); // Log here instead of outside the observable
}, error=> this.error = error)
remember that all http requests (such as this.http.get) are asynchronous, either returning observable or promise. So you only have the proper result before it the value has been emitted (in the case of an observable) or resolved (promise).
本文标签: javascriptangular 5 consoling http toPromise() request returns undefinedStack Overflow
版权声明:本文标题:javascript - angular 5 consoling http toPromise() request returns undefined - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745405306a2657222.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论