我尝试从angular2
向node.js发出http.get()请求在CartService.ts ..
@Injectable()
export class CartService {
private CartUrl: string = '../cart'; // URL to Web API
private headers: Headers = new Headers({'Content-Type': 'application/json'});
constructor(private http: Http) {}
public getCart(): Promise<Cart> {
return this.http.get(this.CartUrl)
.toPromise()
.then(response => response.json().data as Cart)
.catch(this.handleError);
}
public handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
和app.component.ts ...
export class AppComponent implements OnInit {
constructor (private cartService: CartService){}
cart : Lecture[] = [];
DBinfo : Cart;
ngOnInit(): void {
this.getCart();
}
private getCart() : void{
this.cartService.getCart()
.then(DBinfo => this.DBinfo = DBinfo ,
()=>console.log("The data is... "+this.DBinfo));
}
来自nodejs的和index.js ..
router.get('/cart', function (req, res,next) {
var cart = {
"email": "sAAAA@gmail.com",
"item" : "bread"
};
res.json(cart);
});
当使用this.getCart()执行ngOnInit时,
console.log(&#34;数据是......&#34; + this.DBinfo));
刚打印出来的数据是......未定义的&#34;
如何从node.js中获取数据..?
感谢您抽出时间阅读本文:)
答案 0 :(得分:0)
来自then()
的第二次回调是错误回调!
.then(data => ..., err => console.log(err));
。
因此,当第二个回调被执行时,您的请求中似乎有任何错误!
您从node.js返回的对象没有data
属性:
.then(response => response.json() as Cart)
我会使用Observables
,这应该可以解决问题:
public getCart(): Observable<Cart> {
return this.http.get(this.CartUrl)
.map(response => response.json() as Cart) // NO '.data' !!??
.catch(this.handleError);
}
public handleError(error: any) {
console.error('An error occurred', error);
return Observable.of(null);
}
private getCart(): void {
this.cartService.getCart()
.subscribe(DBinfo => this.DBinfo = DBinfo,
err => console.log(err),
() => console.log('done'));
}