我在项目中使用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,
) { }
这是我的 get 和 post 方法之一的示例
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;
从
HttpModule
中的@nestjs/common
导入TimeModule
并将其添加到imports
数组中。
从
HttpService
中的 providers
数组中删除 TimeModule
。您可以直接在TimeService
中导入。
import { HttpModule } from '@nestjs/common';
...
@Module({
imports: [TerminalModule, HttpModule],
providers: [TimeService],
...
})
时间服务:
import { HttpService } from '@nestjs/common';
如果您的响应类型是
Observable
类型的 AxiosResponse
,则也将这两个导入到服务文件中 TimeService
。
import { Observable } from 'rxjs';
import { AxiosResponse } from 'axios';
作为参考,请查看 http-module 和这篇 post。
不要在提供者中传递 HttpService。仅导入 HttpModule。
这有效!
只需导入这个
import { HttpModule} from '@nestjs/axios';
然后将其添加到@Module的导入中,不要在providers中添加HttpService。