這裏是有可能爲你工作,如果你使用的是4.3角和更高,並且希望使用新的HttpClient和HttpHeaders。
這裏是不與基本授權的呼叫的服務:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
const url = `https://sampleapi.com`;
@Injectable()
export class BasicService {
private _headers = new HttpHeaders().set('Content-Type', 'application/json');
constructor(private httpClient: HttpClient) { }
getWithBasicAuth(): Observable<any> {
const headers = this._headers.append('Authorization', 'Basic QjNYRnZ6S1Jk');
return this.httpClient.get<any>(url, { headers : headers });
}
}
下面是將消耗上面的服務的組件。
import { Component, OnInit } from '@angular/core';
import { BasicService } from '../services/basic.service';
@Component({
selector: 'app-basic',
templateUrl: './basic.component.html',
styleUrls: ['./basic.component.css']
})
export class BasicComponent implements OnInit {
dataFormService: any;
constructor(private basicService: BasicService) { }
ngOnInit() {
this.basicService.getWithBasicAuth().subscribe(data => this.dataFormService = data);
}
}
您可能希望從any
改變從服務的返回類型更合適一些。
如果你愛上了這個框架是這樣,你爲什麼不以涵蓋HTTP相關的問題一個基本的教程? (有很多) –
或者也許只是谷歌周圍:https://angular.io/guide/http(角度http請求的第一個結果) –