Angular-无法从api

时间:2018-06-26 16:15:32

标签: angular

错误:

  

获取https://od-api.oxforddictionaries.com/api/v1/entries/en/hi 403   (禁止)。

xyz.service.ts

import { Injectable } from '@angular/core';
import { HttpErrorResponse } from "@angular/common/http";
import {Http, Response} from '@angular/http';
import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';

@Injectable({
providedIn: 'root'
})
export class XyzService {

   word: String = "aardvark";
   constructor(private _http: HttpClient) {}
   private handleError(err: HttpErrorResponse) {
   console.log(err.message);
   return Observable.throw(err.message);
  }
   getDictonaryData(name?): any {
       if(name){
          this.word = name
      }

  let headers = new HttpHeaders();
  headers.append('Accept','application/json');
  headers.append('app_id','4e**91');
  headers.append('app_key','7d0740a128b****843d6f');

  let myResponse = this._http.get('https://od- 
  api.oxforddictionaries.com/api/v1/entries/en/'+this.word,{headers:headers
 });
  return myResponse;

  }
 }

app.component.ts

 import { Component, OnInit } from '@angular/core';
 import { ActivatedRoute, Router } from '@angular/router';
 import { XyzService } from './xyz.service';
 import { HttpClient } from '@angular/common/http';
 import { catchError } from 'rxjs/operators';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
name:string;
dictData:any;


 constructor(private _route: ActivatedRoute, private router: Router, private 
xyzService: XyzService, ) {}

 getData() {
  this.xyzService.getDictonaryData(this.name).subscribe(
    data => {

        this.dictData = data;
          console.log(this.dictData);
          } ,

      error => {
          console.log("some error occured");
          console.log(error.errorMessage);
      }
   );

  }}

app.component.html

<input id="name" type="text" [(ngModel)]="name"/>
<button (click)="getData()"> Get Data </button>

<div class="row" *ngIf="dictData">
<h2>{{dictData["results"][0]["lexicalEntries"][0]["entries"][0]["senses"][0] 
["definitions"]}}

</h2>
</div>

以前我也遇到了另一个错误

  

'在请求的请求中没有Access-Control-Allow-Origin标头   资源”。

但是在添加了“ Moesif Origin&CORS Changer”扩展名之后,该错误消失了。 但是我仍然遇到另一个错误:

GET https://od-api.oxforddictionaries.com/api/v1/entries/en/hi 403 (Forbidden).

1 个答案:

答案 0 :(得分:0)

让我们尝试一下

httpParams = httpParams.set('params1', paramsValue);
return this.httpClient.get<any>(url, {
      headers: httpHeaders,
      params: httpParams
    });