简体   繁体   English

使用来自angular2对node.js的http.get()请求获取未定义的数据?

[英]undefined data using http.get() request to node.js from angular2?

i'm trying to http.get() request to node.js from angular2 我正在尝试从angular2向node.js发出http.get()请求

in CartService.ts.. 在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);
    }

} }

and app.component.ts... 和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));

}

and index.js from nodejs.. 和来自nodejs的index.js。

router.get('/cart', function (req, res,next) {

    var cart = {
        "email": "sAAAA@gmail.com",
        "item" : "bread"
    };

    res.json(cart);
});

when ngOnInit excuted with this.getCart(), 当ngOnInit用this.getCart()执行时,
console.log("The data is... "+this.DBinfo)); console.log(“数据为...” + this.DBinfo));
just printed that "The data is... undefined" 刚刚打印出“数据未定义...”

how can I get data from exactly from node.js..? 我怎样才能准确地从node.js ..获取数据?
thanks for your time to read this :) 感谢您抽出宝贵时间阅读本:)

Second callback from then() is the error-callback! then()第二个回调是错误回调!

.then(data => ..., err => console.log(err)); .

So as the second callback is executed, there seems to be any error during your request! 因此,在执行第二个回调时,您的请求期间似乎有任何错误!

And your returned object from node.js has no data property: 而且从node.js返回的对象没有data属性:

.then(response => response.json() as Cart)

I would use Observables , this should do the trick: 我将使用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'));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM