我有两个API并执行以下步骤:
我已经尝试了太多的选项,所有这些选项似乎都适用于旧版本的角度。
问题 当我进行第一次api调用(ping)时,它返回ID和令牌。我需要调用另一个api2将其作为用户名和密码传递(我在POSTman中将这些Returened值作为username / passsword)。我尝试设置一些授权标题,但它没有工作,并抛出401
我已经经历了很多例子,但那些与角度版本不匹配
我-HTTP-interceptor.ts
import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest,HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
@Injectable()
export class MyHttpInterceptor implements HttpInterceptor {
constructor() { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log("intercepted request ... ");
// Clone the request to add the new header.
const authReq = req.clone({ headers: req.headers.set( 'Authorization', 'Basic dmlld2VyLTFAaXR0aWFtLmNvbTp2aWV3ZXIx')});
console.log("Sending request with new header now ...");
// console.log(authReq)
//send the newly created request
return next.handle(authReq)
}
}
App.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyHttpInterceptor } from './my-http-interceptor'
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
],
imports: [
BrowserModule,
HttpClientModule
],
providers: [
{
provide: HTTP_INTERCEPTORS,
useClass: MyHttpInterceptor,
multi: true
}
],
bootstrap: [AppComponent]
})
导出类AppModule {}
App.compoent.ts
import { Component } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import {RequestOptions, Request, RequestMethod,Http,Headers} from '@angular/http';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(public http: HttpClient) {}
public ping() {
this.http.get('https://Api1.com')
.subscribe(
data => console.log(data));}
public api2(){
this.http.get('https://Api2.com')
.subscribe(
data => console.log(data));}
}
}
app.component.html
<button (click)="ping()">Method 1</button>
<button (click)="api2()">Method 2</button>