在 LoopBack 4 中,我们使用存储库设计模式来访问数据。为了通过 id 找到用户实例,您需要通过依赖注入获取UserRepository 的实例。引用https://loopback.io/doc/en/lb4/Repository.html:
存储库正在向模型添加行为。模型描述数据的形状,存储库提供类似 CRUD 操作的行为。这与模型也实现行为的 LoopBack 3.x 不同。
更新的解决方案
要获取 Repository 类的实例,您可以使用 Service Locator 设计模式并从 LoopBack 的 REST 层提供的 per-request Context 对象中获取实例。
import {MIDDLEWARE_CONTEXT, RequestContext} from '@loopback/rest';
import {UserRepository} from '../repositories';
function expressHandler(req, res, next) {
const ctx = (req as any)[MIDDLEWARE_CONTEXT];
const userRepo = await ctx.get<UserRepository>('repositories.UserRepository');
const users = await userRepo.find({limit: 10});
// render your view
}
我们正在讨论如何在 GitHub 拉取请求 loopback-next#6793 中更轻松地实现此用例,欢迎随时加入讨论。
原始答案
我建议您编写一个 LoopBack 4 控制器,而不是为您呈现的页面编写 Express 路由;并注入 Express Response 对象以允许您呈现 HTML 视图,如 https://loopback.io/doc/en/lb4/Accessing-http-request-response.html#inject-http-response 中所述
import {Response, RestBindings, oas} from '@loopback/rest';
import {inject} from '@loopback/core';
import {UserRepository} from '../repositories';
export class PingController {
constructor(
@inject(RestBindings.Http.RESPONSE)
private response: Response
@repository(UserRepository)
public userRepository: UserRepository,
) {}
// Hide this endpoint from OpenAPI spec generated for the app
@oas.visibility('undocumented')
@get('/users')
list(): Response {
// Access User data via this.userRepository API
const users = await this.userRepository.find({limit: 10});
// Access the response object via `this.response`
this.response.render('users', {users});
// Return the HTTP response object so that LoopBack framework skips the
// generation of HTTP response
return this.response;
}
}
话虽如此,如果您已经知道如何在 Express 路由中从 LB4 应用程序访问 DataSource 实例,那么您也可以从路由中手动实例化 Repository 类:
const db = // your datasource
this.app.get('/hello', async function (_req: Request, res: Response) {
const repo = new UserRepository(db);
const users = await this.userRepository.find({limit: 10});
});