Common Errors in Angular 2 due to TSLint

I am encountering multiple errors in my code. I am using Angular 2 with TSLint:

constructor(http: Http) {
    this.http = http;
--> let currentUser = JSON.parse(localStorage.getItem("currentUser"));
    this.token = currentUser && currentUser.token;
}

I am getting the following error in currentUser:

message: 'expected variable-declaration: 'currentUser' to have a typedef
;

public loginC (username: string, password: string): Observable<boolean> {
    return this.http.post( authURL + loginURL,
                     --> JSON.stringify({ password: password, username: username }))
    .map((response: Response) => {
        let token: string = response.json() && response.json().token;
        if (token) {
          this.token = token;
      --> localStorage.setItem("currentUser", JSON.stringify({token: token, username: username}));
            return true;
        } else {
            return false;
        }
    });
}

Additionally, in

password: password, username: username
I am encountering:
message: 'Expected property shorthand in object literal.
I have a better understanding now. And finally, I can define a simple model: any {};

export class LoginComponent {
--> public model: any = {};
public loading: boolean = false;
public error: string = "";
constructor (private router: Router, private authenticationService: ServerDataComponent) {
    // 
}

public login(): void {
    this.loading = true;
    this.authenticationService.loginC(this.model.username, this.model.password)
        .subscribe(result => {
           --> if (result === true) {
                this.router.navigate(["/table_per"]);
            } else {
                this.error = "Incorrect login and/or password entered";
                this.loading = false;
            }
        });
}

Using 'any' is not allowed -

Type declaration of 'any' is forbidden
;

For the result -

expected arrow-parameter: 'result' to have a typedef

Answer №1

To ensure that the variable declaration 'currentUser' has a typedef, create an interface for your custom type.

export interface User {
  token: string;
}

Then, use this interface to set the type as shown below.

let currentUser: User = JSON.parse(localStorage.getItem("currentUser"));

To address the issue of expected property shorthand in an object literal, utilize the shorthand syntax when the key name matches the variable name.

JSON.stringify({token, username})

If you encounter the error 'Type declaration of 'any' is forbidden,' consider changing the type to 'Object' or create a new interface for your model.

public model: Object = {};

Lastly, to resolve the expected arrow-parameter 'result' to have a typedef, specify the type of the parameter as shown below.

.subscribe((result: boolean) => {

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

Angular Jasmine Test: Anticipated the invoked spy to have been executed

Examining a confirmation dialog in Angular 8 has led to an interesting discovery: one test passes while others fail, even though they are quite similar. The tests being conducted are for three statuses: Approve, Reject, and Reset. Interestingly, the test f ...

Perform an action after the Ngx Bootstrap modal has been hidden

My modal features a login button: <button type="button" (click)="save()" class="btn btn-primary"> login </button> Upon clicking the button, my desired outcome is to: first hide the modal, and second navigate to another route. However, ...

What is the best way to determine which option is most suitable: types, classes, or function types in TypeScript for

Currently, I am developing a small todo command line utility with a straightforward program structure. The main file is responsible for parsing the command line arguments and executing actions such as adding or deleting tasks based on the input provided. E ...

Exploring the capabilities of extending angular components through multiple inheritance

Two base classes are defined as follows: export class EmployeeSearch(){ constructor( public employeeService: EmployeeService, public mobileFormatPipe: MobileFormatPipe ) searchEmployeeById(); searchEmployeeByName(); } ...

angular8StylePreprocessorSettings

I'm currently trying to implement the approach found on this tutorial in order to import scss files through stylePreprocessorOptions in Angular 8. However, I'm encountering an error stating that the file cannot be found. Any suggestions on how to ...

Key constraints in generics: a key must belong to a distinct object type

Is there a way to enhance the safety of this function even further? Consider this object/shape: export const initialState: State = { foods: { filter: '', someForm: { name: '', age: 2, ...

Exploring methods for efficiently handling extensive XLSX files in a Node.js environment

Currently, I am utilizing the ts-xlsx library on the server side to read data. The process involves reading data from the frontend as a byte array using file-reader and then sending this byte array to a library to process the data. However, in cases where ...

NPM IP library susceptible to Server-Side Request Forgery (SSRF) vulnerabilities

Received Security Alert from GitHub's Dependabot Regarding an Issue in My Angular Repository A security vulnerability has been identified in all versions of the NPM package "ip," allowing a malicious actor to execute arbitrary code and access sensiti ...

Substitute the existing path with an alternative route

To move to a different route in Angular 2.0, we typically use route.navigate( [ 'routeName' ] ). However, this approach adds the current route to the browser's history. Is there a technique available to substitute the current route in the ...

Can you explain the purpose of this TypeScript code snippet? It declares a variable testOptions that can only be assigned one of the values "Undecided," "Yes," or "No," with a default value of "Undecided."

const testOptions: "Undecided" | "Yes" | "No" = "Undecided"; Can you explain the significance of this code snippet in typescript? How would you classify the variable testOptions? Is testOptions considered an array, string, or another d ...

Having trouble retrieving data in the service. Unable to subscribe to it from other components

userService.ts private APIUrl: string = environment.APIUrl; constructor(private inService: API, private httpClient: HttpClient) { } private _userDataDashboard$ = new ReplaySubject<UserDetailsDashboard>(1); getUserDetailsSubject(): Obser ...

Launching a Material UI Modal nested within a parent component

I have a table displaying various teams. Each row in the table has a menu option that, when clicked, should open either a modal or a dialog box. I want to keep the table, menu functionality, and modals as separate components for better organization. Here&a ...

Module logo.svg not found? Error in Typescript

Integrating package: vue-svg-loader. Established the file svg.d.ts with the content below: declare module '*.svg' { const content: any export default content } Utilizing it in a component in the following manner: import register from &apo ...

Using NgRx to observe state changes in a service instead of relying on an Effect

Is it possible for a service to monitor state changes and make HTTP calls based on the state value without being triggered by an effect (NgRx)? In other words, can a service react to a portion of the store and eliminate the need for an effect to be involve ...

What could be causing this error in a new Next.js application?

After multiple attempts, my frustration and disappointment in myself are causing a headache. Can someone please assist me? I am trying to create an app using the following command: npx create-next-app@latest --ts Immediately after running next dev, I enco ...

What is the method to create a universal type by utilizing attributes from a different type?

In building a type, I aim to create one that can accept the type of another object and generate a different type based on specific properties in that object. Illustrating this concept through code: // Definition representing the types of inputs shown on UI ...

Angular's ExpressionChangedAfterItHasBeenCheckedError is a common issue that developers encounter

This message continues the discussion about a persistent issue I have been facing. Here is the link to the original thread on Stack Overflow: stackoverflow.com/questions/44596418/angular-throws-expressionchangedafterithasbeencheckederror-with-textarea Af ...

Incorporate Angular Material into a personalized library

In my quest to create a reusable library for various projects, I decided to embark on building my own from scratch. The process began with the formation of a new application solely dedicated to housing this library: ng new lib-collection cd lib-collection ...

Automatically upgrade packages to the latest version 12.0.0-next.0 with ng update

Recently, I've encountered an issue while updating my projects from Angular 10 to Angular 11. Whenever I run ng update, some packages are being upgraded to version 12.0.0-next.0 instead of the stable release. It seems like ng update is installing pre- ...

Guidelines for integrating a SOAP asmx service into an Angular+8 application using XML implementation

Here is the code snippet I'm struggling with: var xmlItemAll = '<?xml version="1.0" encoding="utf-8"?>' + '<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:x ...