soon530 / nestjs-study

來學一下nestjs吧!
0 stars 0 forks source link

HTTP Module #24

Open soon530 opened 1 year ago

soon530 commented 1 year ago

https://ithelp.ithome.com.tw/articles/10278215

很常見的功能,之後會用到。

soon530 commented 1 year ago

要先安裝套件。

 % yarn add @nestjs/axios
yarn add v1.22.19
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
warning " > swagger-ui-express@4.5.0" has unmet peer dependency "express@>=4.0.0".
warning " > ts-loader@9.4.1" has unmet peer dependency "webpack@^5.0.0".
[4/4] 🔨  Building fresh packages...

success Saved lockfile.
success Saved 4 new dependencies.
info Direct dependencies
└─ @nestjs/axios@1.0.0
info All dependencies
├─ @nestjs/axios@1.0.0
├─ axios@1.1.3
├─ follow-redirects@1.15.2
└─ proxy-from-env@1.1.0
✨  Done in 9.12s.
soon530 commented 1 year ago

app.controller.ts 要從service去要資料。

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @Get('all')
  getTodos() {
    return this.appService.getTodos();
  }
}

app.module.ts import需要的module進來。

import {HttpModule} from "@nestjs/axios";

@Module({
  imports: [HttpModule],
  controllers: [AppController, TodoController],
  providers: [AppService],
})

app.service.ts 這裡就可以拿來用了。

import {HttpService} from "@nestjs/axios";
import {map, Observable} from "rxjs";
import {Todo} from "./common/todo.model";
import {Agent} from "https";

@Injectable()
export class AppService {
  constructor(
      private readonly http: HttpService
  ) {}

  getTodos(): Observable<Todo> {
    const httpsAgent = new Agent({ rejectUnauthorized: false });
    return this.http.get('https://jsonplaceholder.typicode.com/todos', { httpsAgent }).pipe(
        map((res) => res.data)
    );
  }
}

todo.model.ts 有個model去定義一下我們要回傳的資料。

export interface Todo {
    userId: number;
    id: number;
    title: string;
    completed: boolean;
}
soon530 commented 1 year ago

來一下試錯學習。

app.module.ts 如果沒有導入HttpModuleimports: []中呢?

import {HttpModule} from "@nestjs/axios";

@Module({
  imports: [],
  controllers: [AppController, TodoController],
  providers: [AppService],
})

app.service.ts 這時候去做注入,就會出錯了。

import {Injectable} from '@nestjs/common';
import {HttpService} from "@nestjs/axios";

@Injectable()
export class AppService {
  constructor(
      private readonly http: HttpService
  ) {}
}

這裡直接要你去檢查一下HttpService有沒有被匯入。

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

Potential solutions:
- If HttpService is a provider, is it part of the current AppModule?
- If HttpService is exported from a separate @Module, is that module imported within AppModule?
  @Module({
    imports: [ /* the Module containing HttpService */ ]
  })
soon530 commented 1 year ago

不是很好懂,之後再來研究。

  getTodos(): Observable<Todo> {
    const httpsAgent = new Agent({ rejectUnauthorized: false });
    return this.http.get('https://jsonplaceholder.typicode.com/todos', { httpsAgent }).pipe(
        map((res) => res.data)
    );
  }