如何在扩展的HttpClass中访问公共方法?附自定义AppHttp实现代码
AppHttp Class First off, let’s make sure we’re aligned: your AppHttp class extends Angular’s Http (I’m assuming this is Angular 2+ given the @Injectable() decorator), and you want to call its public methods like presetPetition from other parts of your app. Here’s a straightforward, step-by-step solution:
Step 1: Confirm Method Accessibility
In TypeScript, class methods are public by default unless marked private or protected. Your presetPetition method is already public, so that’s covered. For any future methods you add, just avoid restricting their access if you need to call them externally.
Step 2: Provide AppHttp in Your Module
First, ensure your custom HTTP class is registered as a provider in your app module (or feature module) so Angular can inject it. You can either replace the default Http with your AppHttp, or provide it as a standalone service:
// app.module.ts import { NgModule } from '@angular/core'; import { Http, ConnectionBackend, RequestOptions } from '@angular/http'; import { AppHttp } from './app.http'; // Factory to create AppHttp instances export function appHttpFactory(backend: ConnectionBackend, options: RequestOptions) { return new AppHttp(backend, options); } @NgModule({ providers: [ // Option 1: Replace default Http with AppHttp { provide: Http, useFactory: appHttpFactory, deps: [ConnectionBackend, RequestOptions] }, // Option 2: Provide AppHttp directly for explicit injection AppHttp ] }) export class AppModule {}
Step 3: Inject & Call Public Methods
Now inject AppHttp (or Http if you used Option 1) into any component or service where you need to use its methods. Here’s an example component:
// example.component.ts import { Component, OnInit } from '@angular/core'; import { AppHttp, Type } from './app.http'; @Component({ selector: 'app-example', template: '<button (click)="switchToPrinterPetition()">Use Printer API</button>' }) export class ExampleComponent implements OnInit { constructor(private appHttp: AppHttp) {} ngOnInit() { // Call method on component initialization this.appHttp.presetPetition(Type.AUTH); } switchToPrinterPetition() { // Call method on user action this.appHttp.presetPetition(Type.PRINTER); console.log('Switched to Printer API configuration'); } }
Quick Tips
- Injecting
AppHttpdirectly (Option 2) makes your code more readable, as it’s clear you’re using your custom implementation. - If multiple components modify
typesOnor other internal state, add safeguards (like checks or locks) to ensure consistency across requests.
That’s all! You should now be able to access all public methods of your AppHttp class anywhere in your application.
内容的提问来源于stack exchange,提问作者francojay

