简体   繁体   English

如何从angular 4传递参数以访问REST API数据

[英]How to pass parameters from angular 4 to access REST API data

I have created the service to access the REST API data but when i hit the url from the Angular application end then it gives me this error in the console. 我已经创建了用于访问REST API数据的服务,但是当我从Angular应用程序端访问URL时,它将在控制台中显示此错误。

Failed to load http://<SERVER.URL.FROM.SERVER>/api/invoice-details/121: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 403.

So for that the backend guy gave some authentication parameters like 为此,后端人员提供了一些身份验证参数,例如

在此处输入图片说明

So he is telling me to pass the parameters For Authentication to access the data in my Angular application. 因此,他告诉我传递用于身份验证的参数以访问Angular应用程序中的数据。 Otherwise i can get the same error like CORS. 否则我会得到像CORS一样的错误。

So my question is how to pass the parameters from my end. 所以我的问题是如何从末端传递参数。 I have written the code like this in the user.service.ts where all my services are there. 我已经在所有我的服务都在那里的user.service.ts中编写了这样的代码。

import { Http, Headers, RequestOptions, Response } from '@angular/http';

@Injectable()
export class UserService {

    private headers = new Headers({ 'Content-Type': 'application/json', 'charset': 'UTF-8' });
    private options = new RequestOptions({ headers: this.headers, withCredentials: true });

    constructor(private http: Http, private config: AppConfig) {}

getSupplierBasicInfo(){
        return this.http.get(this.config.apiUrl + 'api/supplier-basic-info/121')
        .map(response => response.json());
    }
}

In the component i am calling the service like this: 在组件中,我这样调用服务:

import { Component, OnInit } from '@angular/core';
import { UserService } from '../../services/user/user.service';

@Component({
  selector: 'app-invoice',
  templateUrl: './invoice.component.html',
  styleUrls: ['./invoice.component.css']
})
export class InvoiceComponent implements OnInit {
  invoiceDetails: any[];
  constructor(private _userService: UserService) { 
    console.log('Invoice Details loaded!');
  }

  ngOnInit() {
    this._userService.getInvoiceDetails()
    .subscribe(data => this.invoiceDetails = data);
  }
}

Data binding is like this: 数据绑定是这样的:

<table class="table table-striped">
    <thead class="thead-dark">
      <tr style="background-color:#55555A; color:#ffffff">
        <th scope="col">Req ID</th>
        <th scope="col">Date</th>
        <th scope="col">Category</th>
        <th scope="col">Details</th>
        <th scope="col">Status</th>
        <th scope="col">View</th>
        <th scope="col">Download</th>
      </tr>
    </thead>
    <tbody>
        <tr *ngFor="let item of orderDetails">
            <td>{{ item.title }}</td>
            <td>{{ item.field_date }}</td>
            <td>{{ item.field_date }}</td>
            <td>{{ item.field_first_name }}</td>
            <td>{{ item.field_upload_invoice }}</td>
            <td><i class="fa fa-eye" aria-hidden="true"></i></td>
            <td><span class="glyphicon glyphicon-download"></span></td>
        </tr>
    </tbody>
  </table>

So can anybody help me that how to pass the parameters to get the data in my application. 因此有人可以帮助我如何传递参数以获取应用程序中的数据。

Imports: 进口:

import { Http, Headers, URLSearchParams, RequestOptions } from '@angular/http';

Headers: 标头:

    private headers = new Headers([
            { 'credentials': 'same-origin' },
            { 'Access-Control-Allow-Origin': '*' },
            //instead of * you can specify your host 
            { 'Access-Control-Allow-Credentials': 'true' },
        ]);
        //private params: URLSearchParams = new URLSearchParams(); 
        private options: RequestOptions = new RequestOptions({ headers: this.headers,
withCredentials: true 
});

Request: 请求:

this.options.search = this.params;
this.http.get(`${this.host}${this.url}`, this.options)
            .map(result => result.json());

You can also specyfi CORS on web api configuration file to add headers to every request. 您还可以在Web api配置文件中指定CORS,以将标头添加到每个请求。

Try the below thing in web.config file 尝试在web.config文件中进行以下操作

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
  </customHeaders>
</httpProtocol>

This will definitely help you. 这一定会对您有帮助。

暂无
暂无

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

相关问题 如何使用Spring Boot在angular 4中的HTTP Get方法中传递分页对象以使用REST API从REST API中获取数据 - How to pass Pagination object in HTTP Get method in angular 4 for fetching data from REST API using spring boot 如何将参数从 angular 传递到我的 nodejs API? - How do I pass parameters from angular into my nodejs API? 如何将多个参数从 angular 8 传递到 .NET Core API - How to pass multiple parameters from angular 8 to .NET Core API 如何在有角度的应用程序中将查询参数传递给服务内的REST API? - How will i pass query parameters to REST API inside a service in an angular application? 我有单独的节点REST api和单独的Angular 4接口。 我可以将此Angular 4中的数据传递给单独的REST API吗? - I have seperate node REST api and separate Angular 4 interface. Can I pass data from this Angular 4 to Separate REST api? 如何在 ZC31C335EF37283C451B18BA0DD317DE1 中通过 Django rest 框架 API - How to pass Django rest Framework API in Angular 9? 如何将一些字符串或数据从 API 传递到 angular 6 中的 angular 组件? - How to pass some string or data from API to an angular component in angular 6? 如何在 Angular 中实时异步地从 REST API 获取数据 - How to get data from a rest API asynchronously in realtime in Angular 如何从Rest API获取数据到我的视图-Angular 6 - How to get data from a rest api into my view - Angular 6 了解如何调用REST Api并在Angular 2中显示响应中的数据 - Understanding how to call a REST Api and displaying the data from the response in Angular 2
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM