Angular 角度-无法从api获取数据
错误: 得到403 (禁止) xyz.service.tsAngular 角度-无法从api获取数据,angular,Angular,错误: 得到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/htt
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>
让我们试试这个
httpParams = httpParams.set('params1', paramsValue);
return this.httpClient.get<any>(url, {
headers: httpHeaders,
params: httpParams
});
httpParams=httpParams.set('params1',paramsValue);
返回此.httpClient.get(url{
标题:httpHeaders,
参数:httpParams
});
我收到的错误很少。找不到名称“httpParams”。类型“typeof HttpParams”上不存在属性“set”。若要像此人一样,请让HttpParams=new HttpParams().set('categoryId',String(categoryId));首先在不使用Angular的情况下测试API(例如使用Fiddler或Swagger)。
httpParams = httpParams.set('params1', paramsValue);
return this.httpClient.get<any>(url, {
headers: httpHeaders,
params: httpParams
});