typescript 如何使用 Angular2 使用 REST API?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39905586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:54:45  来源:igfitidea点击:

How to consume REST API with Angular2?

javascriptrestangulartypescript

提问by Elkin

This is my demo code:

这是我的演示代码:

products.service.ts

产品.服务.ts

getProducts(){
 this.headers = new Headers();
 this.headers.append("Content-Type", 'application/json');
 this.headers.append("Authorization", 'Bearer ' + localStorage.getItem('id_token'));
 return this.http.get('http://mydomain.azurewebsites.net/api/products',{headers:headers}).map(res => res.json().data);
}

products.component.ts

products.component.ts

constructor(private productsService: ProductsService) { }

ngOnInit() {
 this.productsService.getProducts().subscribe((res) => {
    console.log(res); 
 });
}

Is it nescessary to import something in the ngModuledecorator to consume a REST API or my code is wrong? I can get the desired data with Postman Chrome Extension but not with Angular 2 code.

是否有必要在ngModule装饰器中导入一些东西来使用 REST API 或者我的代码是错误的?我可以使用 Postman Chrome 扩展程序获取所需的数据,但不能使用 Angular 2 代码。

I hope to have explained my problem well.

我希望能很好地解释我的问题。

Update

更新

These are the errors i get:

这些是我得到的错误:

enter image description here

在此处输入图片说明

回答by Elkin

Sorry for making you waste your time.

抱歉让你浪费了你的时间。

This was the problem:

这就是问题所在:

app.module.ts

app.module.ts

providers: [
    ProductsService,
    // { provide: XHRBackend, useClass: InMemoryBackendService }, // in-mem server
    // { provide: SEED_DATA,  useClass: InMemoryDataService }     // in-mem server data
  ]

After commenting the in-mem serverand and the in-mem server datathe problem dissapeared.

在评论in-mem server和之后in-mem server data问题消失了。

回答by Brad

You're not setting the headers in the request. You declare the Headersobject but you don't actually do anything with it.

您没有在请求中设置标头。您声明了该Headers对象,但实际上并未对其进行任何操作。

You need to set them in the getfunction like this:

您需要在get函数中设置它们,如下所示:

return this.http
           .get('http://mydomain.azurewebsites.net/api/products', { headers: headers })
           .map(res => res.json().data);

回答by Khang ?ào

I'd suggest you use ngx-rest-ex: https://www.npmjs.com/package/ngx-rest-ex

我建议你使用ngx-rest-exhttps: //www.npmjs.com/package/ngx-rest-ex

npm i -S ngx-rest-ex

It's convenient, you just need to specify the corresponding decorator on top of the method and the return type, it will replace your method body. The return type can be either Promiseor Observabledepending on the HTTP METHOD annotation that you specified.

很方便,你只需要在方法顶部指定相应的装饰器和返回类型,它就会替换你的方法体。返回类型可以是PromiseObservable取决于您指定的 HTTP METHOD 注释。

My demo code for your case:

我的案例演示代码:

import { Injectable, Injector } from '@angular/core';
import { BaseUrl, GET, RESTClient } from 'ngx-rest-ex';

import { Product } from './models';


@Injectable({
    providedIn: 'root'
})
@BaseUrl('http://mydomain.azurewebsites.net/api/')
export class ApiService extends RESTClient {

    constructor(injector: Injector) { super(injector); }

    protected getDefaultHeaders() {
        return {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + localStorage.getItem('id_token')
        };
    }

    @GET('products')
    getProducts(): Promise<Product[]> {
        return;
    }
}