如何使用Angular 6连接到API

时间:2019-07-12 21:40:51

标签: angular api http get

我的Api包含一些图像,使用该API我得到了错误 和其他Api一起工作很好,我想听听您的想法。

香草javascript

//https://api.github.com/users/koushikkothagal
fetch('https://demo.evona.ba:3100/banners/0')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});

被评论的Api工作正常,但另一个API给我错误 enter image description here

再次,我使用Angular来获取相同的Api,再次出现错误,另一个Api正常工作

app.compoennt.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { ApiService} from './api.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
posts;
constructor(private http: HttpClient, private api: ApiService){}
ngOnInit(){
this.api.getData().subscribe(api => {
  this.posts= api; 
  console.log(this.posts)
}, 
(err: HttpErrorResponse) => {
  if(err.error instanceof Error){
    console.log("CLient-side Error occured")
  }else{
    console.log("Server-side error occured")
  }
})
}
}

api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from 
'@angular/common/http';

const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'text' as 'json'
})
}
@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient){}
//https://api.github.com/users/koushikkothagal
getData(){
return this.http.get('https://demo.evona.ba:3100/banners/0', httpOptions)
 }
  }

有错误 enter image description here

我也有关于终端ID 2222的问题。在哪里放置该ID

0 个答案:

没有答案