Encountering an error code TS5055 when attempting to call an API within a TypeScript constructor

I'm attempting to retrieve a list of customers by calling a GET API from a dashboard constructor as shown below:

      // tslint:disable-next-line:max-line-length
  constructor(public addCustomerDialog: MatDialog, private router: Router, private route: ActivatedRoute, private customerService: CustomerService) {
    this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/login';
    this.customerList = getCustomers();
  }

  getCustomers() {
    const jwt = localStorage.getItem('jwt');

        // making an AJAX call
    this.customerService.getCustomers(jwt).subscribe((res) => { 
      console.log(res);
    }, (err) => { 
        alert('Token expired. Need to login again!');
        this.router.navigateByUrl(this.returnUrl);
        console.log(err);
    });

  }

An error I encounter is:

ERROR in error TS5055: Cannot write file '/home/spartan/Documents/development/ktf-standalone/api/config/main.js' because it would overwrite input file.
  Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig.
error TS5055: Cannot write file '/home/spartan/Documents/development/ktf-standalone/api/controllers/controllerCustomer.js' because it would overwrite input file.
  Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig.
error TS5055: Cannot write file '/home/spartan/Documents/development/ktf-standalone/api/models/customer.js' because it would overwrite input file.
  Adding a tsconfig.json file will help organize projects that contain both TypeScript and JavaScript files. Learn more at https://aka.ms/tsconfig.

I have a tsconfig.json file in the root directory.

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "es2017",
      "dom"
    ],
    "allowJs": true
  }
}

By commenting out a few lines in the constructor, I am able to start my server.

Is calling the API in the constructor the correct approach? Am I overlooking something here?

Project structure: https://i.sstatic.net/lDPZ3.png

Answer №1

To enhance your getCustomers method, consider updating the value of the customerList property within the subscribe callback function. You can achieve this by using code like the following:

this.customerService.getCustomers(jwt).subscribe(
  (res) => this.customers = res.json(),
  (err) => // handle error;
);

Keep in mind that according to Angular documentation, it is recommended to avoid extensive operations in the constructor. Instead, my proposal is having components implement the OnInit interface and execute API requests specifically within the ngOnInit method when implementing said interface.

Answer №2

Sorry for the confusion. I accidentally used the same method name 'getCustomers' in both the component.ts file and the API controller.

While trying to call the method in the component.ts (dashboard.ts) file, Visual Studio auto-imported the method from the API controller without me realizing it.

Once I called the correct method, I was able to solve my problem. This discussion definitely sparked some ideas that helped lead me to the solution.

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

Managing a project with multiple tsconfig.json files: Best practices and strategies

I've got a project structured in the following way: \ |- built |- src |- perf |- tsconfig.json |- typings |- tsconfig.json My main tsconfig.json looks like this: "target": "es6", "outDir": "built", "rootDir": "./src", Now, I need to have a ...

Node.js built-ins require shims, while global variable names are absent

After updating my project using npm-check-updates, I encountered a strange error that stumped me. Despite following the suggested terminal command to install polyfill-node, the issue persisted with no resolution in sight online. The error displayed on the ...

Exploring TypeScript's Conditional Types

Consider this scenario: type TypeMapping = { Boolean: boolean, String: string, Number: number, ArrayOfString: Array<string>, ArrayOfBoolean: Array<boolean> } export interface ElemType { foo: keyof TypeMapping, default: valueof T ...

Dynamic cell editing feature in PrimeNG table

Looking to implement the PrimeNG Table. https://i.stack.imgur.com/bQycr.png Check out the live demo on StackBlitz. The table has three editable columns. The "Property Name" column always displays a text box in edit mode, while the "Property Value Type" ...

explore and view all images within a directory

Hello, I am new to NextJS and encountering some issues. I have a folder in my public directory containing 30 images that I want to import all at once in the simplest way possible, without having to import each image individually by name. Here is the curren ...

Connecting HTML to an AngularFirestore collection using snapshotChanges

In my mobile app, I am using AngularFirestore2v5/rxjs to connect a hybrid Ionicv3/Angularv4 app to a Firestore collection. While binding UI with AngularFirestore.valueChanges works fine, switching to snapshotChanges for retrieving the id is causing some is ...

Angular Material's autocomplete feature allows users to easily search

I am currently working on creating an Angular Material Autocomplete feature. At the moment, I have successfully displayed the options and when selected, the correct name is inserted into the input field. However, my next task is to enable filtering of the ...

Discover the process of dynamically importing JavaScript libraries, modules, and non-component elements within a Next.js

Lately, I have been utilizing Next.js and mastering its dynamic import feature for importing components with named exports. However, I recently encountered a particular npm package that functions only on the client-side (requires window) and has a substant ...

The angular httpTestingController.expectOne method throws an error, even when the httpClient's get method has

I have an issue with my testing in Angular. I am trying to test a simple function within a service: getReports(url: string): Observable<Report[]> { return this.http.get<Report[]>(url); } This is the test that I have written: it(`should c ...

Issue encountered when transferring Angular app to Python Flask

Not sure what information to provide, but I will give as much detail as possible. Currently, my Angular app is running on IIS and utilizing Classic ASP. Everything is working smoothly. There is a dropdown that fetches JSON data to populate a table. Recen ...

Deliver router services for central Angular 2 elements

I am working on an ng2 app where I have the app/app.module and core/core.module. In the core modules, there are some modules that are used at the app top level and only once as mentioned in the official documentation. However, one of these modules requires ...

Tips for adding href in Angular2

Check out this template example: <a href="#" (click)="goToPost()">{{post.title}}</a> Here's the goToPost() function: goToPost() { this.router.navigate(['/post', this.post.id]); } The resulting link will be: mysite.dev/pos ...

Implementing Server-Side API Response Caching in React-Query and Next JS

My server-side rendering setup with react-query is working smoothly. I am aware that react-query stores a cache on the client side to serve data if the query key is fresh and available. Here is the code snippet depicting this setup - // pages/_app.tsx imp ...

Implementing a custom loading spinner in Angular 2

One of the tasks I have is to implement a loading spinner whenever my data is still being processed. Here is an example of my service: ... constructor(private _http:Http) { } getDataFromApi() { return this._http.get('https://api.punkapi.c ...

Having trouble implementing object type switching in Typescript

While in the process of developing an angular application, I stumbled upon a peculiar issue. Some time ago, I crafted this piece of code which performed flawlessly: selectedGeoArea: any receiveStoreEvent(event) { switch (event.constructor) { ca ...

Error in GraphQL query: specified argument is mandatory, yet not supplied

I recently started learning about graphql and encountered an issue with my query. Here is the code I am using: { product { id } } "message": "Field "product" argument "id" of type "String!" is requir ...

Troubleshooting native web worker issues in Angular 11 - Addressing the Element Bug

After upgrading Angular to version 11, I encountered issues with utilizing web workers for heavy data processing in my project. Previously, I used webworkify-webpack (https://www.npmjs.com/package/webworkify-webpack), but it stopped working post-migration. ...

Is it possible for recursive type definitions to handle generics effectively?

I have identified what I believe to be a bug in Typescript and have submitted it as an issue here. Considering that this might not get resolved quickly, I am reaching out for suggestions. Does anyone know of a better solution or workaround than the one pro ...

Conceal the Angular Material toolbar (top navigation bar) automatically when scrolling downwards

In my Angular application, the main navigation consists of a standard toolbar positioned at the top of the page. My goal is to have this navigation bar smoothly scroll up with the user as they scroll down, and then reappear when they scroll back up. I at ...

Encountering a cloning error while using React Typescript and React Router DOM when calling props.history.push

When using props.history.push without passing state, everything works perfectly fine. However, when trying to pass data with state, an error occurs. The error message reads: DOMException: Failed to execute 'pushState' on 'History': func ...