【发布时间】:2017-04-22 09:33:12
【问题描述】:
我正在尝试从 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("数据是……"+this.DBinfo));
刚刚打印出“数据......未定义”
我怎样才能从 node.js 中获取数据..?
感谢您抽出宝贵时间阅读本文:)
【问题讨论】: