Issue encountered in Loopback 4: Error with @repository dependency injection (TypeError: Undefined property 'findOne')

As I set up Bearer Token authentication for my Loopback 4 application, I referenced this implementation guide: https://github.com/strongloop/loopback-next/tree/master/packages/authentication.

Within my

src/providers/auth-strategy.provider.ts
file, I encountered an issue when trying to utilize the @repository decorator to inject a repository object into the constructor for data querying purposes.

The problem arises when calling findOne() on the repository reference initialized by the @repository decorator, resulting in the error:

TypeError: Cannot read property 'findOne' of undefined

Below is the code snippet from my version of auth-strategy.provider.ts:

import {Provider, inject, ValueOrPromise} from '@loopback/context';
import {Strategy} from 'passport';
import {
  AuthenticationBindings,
  AuthenticationMetadata,
} from '@loopback/authentication';
import {IVerifyOptions} from 'passport-http-bearer';
import {ApiClient} from '../models';
import {ApiClientRepository} from '../repositories';
import {Strategy as BearerStrategy} from 'passport-http-bearer';
import {repository} from '@loopback/repository';

// Rest of the TypeScript code...

Answer №1

It seems like the issue you are facing is similar to the one discussed here: https://github.com/strongloop/loopback-next/issues/1835

To solve this problem, make sure to bind the context of your verify function to your class. Otherwise, this will refer to BearerStrategy instead of BearerStrategyProvider, causing this.apiClientRepository to not exist in that class. You can achieve this by binding it as follows:

return new BearerStrategy(this.verify.bind(this));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Update not reflected in parent form when using ValueChanges in Angular's ControlValueAccessor

Here is the code snippet I am currently working with: https://stackblitz.com/edit/angular-control-value-accessor-form-submitted-val-egkreh?file=src/app/app.component.html I have set default values for the form fields, but when clicking the button, the pa ...

Is there a way to simulate Pinia and vue-i18n simultaneously?

Exploring Vue 3's Composition API with a twist: The store.ts file import { ref, Ref } from 'vue'; import { defineStore } from 'pinia'; export const useStore = defineStore('store', () => { const isLoading: Ref<bo ...

Give it a little time before uploading a widget onto the page

As a newcomer to programming, I recently came across this code from an open source project. I am in the process of loading a widget onto a website. Instead of having the widget load instantly, I would like it to wait 10 seconds before displaying. Below i ...

Exploring Angular 6: Unveiling the Secrets of Angular Specific Attributes

When working with a component, I have included the angular i18n attribute like so: <app-text i18n="meaning|description"> DeveloperText </app-text> I am trying to retrieve this property. I attempted using ElementRef to access nativeElement, bu ...

Using TypeScript to implement functions with multiple optional parameters

Imagine having a function like the one shown here: function addressCombo(street1:string, street2:string = "NA", street3?:string) { console.log("street1: " + street1); console.log("street1: " + street2); console.log("street2: " + street3); } I ...

Tips for reorganizing the files within a directory using Visual Studio Code

Is there a way to reformat an entire project folder at once, rather than just one document? I know that I can use the shortcut key Alt+Shift+F or right click on a document and select Format Document. My projects consist of Typescript files in the Angular ...

TailwindCSS applies CSS settings from tailwind.admin.config.js without overriding tailwind.config.js. The @config directive is utilized for this purpose

I'm currently working on a project using Vite and React. I have a tailwind.admin.css file that is similar to the example provided in the documentation. @config './configs/tailwind.admin.config.js'; @tailwind base; @tailwind components; @tai ...

Display a child element depending on a certain condition

Looking to implement a switch higher-order component (HOC) for conditional rendering that mimics a switch statement in ReactTS. <Switch> <Case condition={cond1}> Hello </Case> <Case condition={cond2}> Wor ...

Ensure data accuracy by triggering the cache - implementing SWR hook in Next.js with TypeScript

I recently implemented the swr hook in my next.js app to take advantage of its caching and real-time updates, which has been incredibly beneficial for my project (a Facebook clone). However, I encountered a challenge. The issue arises when fetching public ...

Troubleshooting a TypeScript Problem with React Context

In my AppContext.tsx file, I have defined the following import React, { useState, createContext } from "react"; import { Iitem } from "../utils/interfaces"; interface AppContext { showModal: boolean; setShowModal: React.Dispatch< ...

Converting docx files to PDF in Angular 15 using the "docxjs" library: A step-by-step guide

I am currently utilizing the to generate some docx files and enable downloading, but I am faced with the challenge of converting these files into PDF format. This is my current process: public download(data: any): void { const documentCreator = new D ...

What issue are we encountering with those `if` statements?

I am facing an issue with my Angular component code. Here is the code snippet: i=18; onScrollDown(evt:any) { setTimeout(()=>{ console.log(this.i) this.api.getApi().subscribe(({tool,beuty}) => { if (evt.index == ...

Transform nested properties of an object into a new data type

I created a versatile function that recursively converts nested property values into numbers: type CastToNumber<T> = T extends string ? number : { [K in keyof T]: CastToNumber<T[K]> }; type StringMap = { [key: string]: any }; const castOb ...

The cache does not contain '.chunk-`X`' as requested in Next.js error

Hello everyone, I've encountered a recent issue with my code that previously worked fine. I was using getStaticProps with a cache time of 5 days, but now I'm facing an error related to the title. Here is a more detailed look at the error: error ...

Troubleshooting connectivity issues between Entities in microORM and Next.js

While trying to run my Next.js application in typescript, I encountered the following error: Error - ReferenceError: Cannot access 'Member' before initialization After consulting the documentation at https://mikro-orm.io/docs/relationships#relat ...

What could be the reason for TypeScript inferring the generic type as an empty string?

I have developed a React component known as StateWithValidation. import { useStateWithValidation } from "./useStateWithValidation"; export const StateWithValidation = () => { const [username, setUserName, isValid] = useStateWithValidation( ( ...

Angular project hosting causing malfunctions in route parameters

Encountering a problem with route parameters after deploying my website on namecheap hosting. Routes Setup: const routes: Routes = [ { path: 'women', component: ProductlistingComponent }, { path: 'women/:search_1', component: ...

What is the best way to showcase several images using Sweet Alert 2?

In the process of developing my Angular 2 application, I have incorporated sweet alert 2 into certain sections. I am looking to showcase multiple images (a minimum of two) at the same time in the pop-up. Does anyone have any suggestions on how to achieve ...

Guide on how to connect several Subjects within an object literal to their corresponding Observables in another object literal

I am currently developing a class using Angular and I need to share multiple states associated with that class. To accomplish this, I have created several instances of BehaviorSubject private subjects = { a : new BehaviorSubject<A>(this.a), b ...

The Vue instance seems to be unable to recognize the shims-vue.d.ts file

I encountered an issue with my Vue file. Here is the code snippet: import Vue from 'vue'; import VueRouter from 'vue-router'; export default Vue.extend({ name: 'MyComponentsName', methods: { doRedirect() { this. ...