如何修复“AXIOS_INSTANCE_TOKEN在索引[0]中可用于模块上下文”的问题。

31

我在项目中使用Axios调用一些第三方的端点。但是我似乎不理解这个错误。

Nest can't resolve dependencies of the HttpService (?). Please make sure that the argument 
AXIOS_INSTANCE_TOKEN at index [0] is available in the TimeModule context.

Potential solutions:
- If AXIOS_INSTANCE_TOKEN is a provider, is it part of the current TimeModule?
- If AXIOS_INSTANCE_TOKEN is exported from a separate @Module, is that module imported within TimeModule?
  @Module({
    imports: [ /* the Module containing AXIOS_INSTANCE_TOKEN */ ]
  })

这是模块

@Module({
  imports: [TerminalModule,],
  providers: [TimeService, HttpService],
  controllers: [TimeController]
})
export class TimeModule { }

这是一个服务

@Injectable()
export class TimeService {
    constructor(private httpService: HttpService,
        @InjectModel('PayMobileAirtime') private time: Model<Time>,       
        @Inject(REQUEST) private request: any,

    ) { }

这是我其中一个 getpost 方法的示例。

(注:该段文字已被翻译,保留原有html标签)
 async PrimeAirtimeProductList(telcotime: string) {
        let auth = await this.TimeAuth()
        const productList = await this.httpService.get(`https://clients.time.com/api/top/info/${telcotime}`,
            {
                headers: {
                    'Authorization': `Bearer ${auth.token}`
                }
            }
        ).toPromise();

        return productList.data
    }

文章

const dataToken = await this.manageTimeAuth()
        const url = `https://clients.time.com/api/dataup/exec/${number}`

        const BuyTelcoData = await this.httpService.post(url, {
            "product_id": product_id,
            "denomination": amount,
            "customer_reference": reference_id
        }, {
            headers: {
                'Authorization': `Bearer ${dataToken.token}`
            }
        }).toPromise();

        const data = BuyTelcoData.data;

请提供HttpService的代码。另外,AXIOS_INSTANCE_TOKEN是什么,它在哪里定义? - Kartik Chauhan
我的代码已经更新。 - techstack
尝试在“TimeModule”模块的“imports”数组中添加“HttpModule”。确保先在该模块中进行导入。 - Kartik Chauhan
请查看此链接 https://docs.nestjs.com/techniques/http-module。 - Kartik Chauhan
2个回答

58

@nestjs/common导入HttpModuleTimeModule中,并将其添加到imports数组中。

TimeModuleproviders数组中删除HttpService。您可以直接在TimeService中导入它。

import { HttpModule } from '@nestjs/common';
...

@Module({
    imports: [TerminalModule, HttpModule],
    providers: [TimeService],
    ...
})

时间服务:

import { HttpService } from '@nestjs/common';

如果你的响应类型是AxiosResponse类型的Observable,那么在服务文件TimeService中也要同时导入这两个内容。

import { Observable } from 'rxjs';
import { AxiosResponse } from 'axios';

参考资料,请查看http-module和此文章


1
知道了:此解决方案也适用于新的 import { HttpModule} from '@nestjs/axios'; - deanWombourne

18
不要将HttpService传递给提供商。只导入HttpModule。

谢谢。它起作用了。但是你能解释一下为什么它起作用了吗? - Uzumaki Naruto
因为imports接受导出提供者的模块列表。默认情况下,提供者是封装的。提供者可以直接在服务中使用。这意味着HttpService可以直接在TimeService中使用。请查看此处的文档Nest Modules 这意味着无法注入既不直接属于当前模块也不从导入模块中导出的提供者。因此,您可以将模块的导出提供者视为模块的公共接口或API。 - sandiejat

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接