Error Encountered during Compilation in Typescript-Angular5

I have been working on implementing a login feature with angular5, but I have encountered several issues along the way. While I managed to resolve some of them, I am currently facing a compilation problem:

ERROR in src/app/login/login.component.ts(38,3): error TS2322: Type 'Subscription' is not assignable to type 'Boolean'.
  Types of property 'valueOf' are incompatible.
    Type '() => Object' is not assignable to type '() => boolean'.
      Type 'Object' is not assignable to type 'boolean'.

I understand the error message, however, I am struggling to figure out how to fix it and get my code to function properly. Below is the code snippet from the login.component.ts class:

import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NgForm } from '@angular/forms';
import { FormGroup, FormControl } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';


import { HttpErrorResponse } from '@angular/common/http';
import { UserService } from '../auth/user.services';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
  ngForm: NgForm;
  login: string;
  password: string;
  myForm: FormGroup;
  isLoginError : boolean = false;
  connected : Boolean = false;
  constructor(private userService: UserService, private router: Router) { }

  ngOnInit() {


  }

// Execute this when submit login form
OnSubmit(form){

    console.log(form.value);
    console.log(form.value.login);
  this.connected =   this.userService.authenticate(form.value.login,form.value.password).subscribe((data : any)=>{
    return data.password = form.value.password;
    //return true;
  });

} }

The error occurs at line 38 which corresponds to

this.connected = this.userService.authenticate(form.value.login,form.value.password).subscribe((data : any)=>{

In user.service.ts, the authenticate method is defined as follows:

authenticate(login:string, password:string) :Observable<Boolean> {
console.log('Authenticate ....');
const credentials = {login:login, password:password};
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
console.log('Appended content type ....');
console.log(' Login '+login+' Password '+password+' Headers '+headers);

  return this.http.get<any>(
                '/users?login?'+JSON.stringify(login),
                 { headers }
  ) 
    .map(user => user.password === password); 

}

Can someone help me resolve this error and make my code work correctly?

Answer №1

Utilize the connected variable within the subscribe method.

this.userService.verifyCredentials(form.value.login, form.value.password)
  .subscribe((isMatch: boolean) => {
    this.connected = isMatch;
  });

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

Integrating additional JavaScript into an Ionic 2 project

Imagine we have a foo.js file containing a variable, function, and class that are not yet part of the project. Now suppose we want to access these elements in our home.ts method or make them globally available for use within a home.ts method. How can this ...

I wonder if there is a more effective way to format serial numbers

Could there be a more streamlined solution for this code snippet I have? /** * Converts serial from '86FC64484BE99E78' to '86:FC:64:48:4B:E9:9E:78' * @param serial */ private formatSerial(serial: string): string { retu ...

Is it possible to include a JavaScript reference to an external .d.ts file?

Our online js library (written in pure javascript) is in need of a .d.ts reference to provide users with Intellisense in VS Code without the need for any downloads or installations. ...

I'm encountering an issue with my Angular CLI project where it's showing an error message that says "Module cannot be found."

Currently, I am diving into an Angular-cli tutorial. In one of my component TS files, there seems to be a problem with importing a class from another directory as it is not being recognized. Below is the content of my component file (display-user-data-for ...

Angular's ng-select fails to select the value when generating the dynamic control

Currently, I am working on dynamically adding cities using ng-select in order to have search functionality while entering city names. For example, if I have two city names saved in a form and need to display them in separate ng-select controls when editing ...

Angular2 app is sending empty HTTP headers to the server

My REST api, built using SpringBoot, incorporates JWT for authentication and authorization. To achieve this, I utilize a FilterRegistrationBean. Within this setup, there exists a class called JwtFilter that extends GenericFilterBean. This class is respons ...

Using Angular 2 to implement a custom dropdown feature with the ngModel directive

I've created a unique custom component that displays employment types in a dropdown menu and allows the user to select one. Here is the code for the component: import { Component, OnInit } from "@angular/core"; import { EmploymentType } from '. ...

Is it possible to convert any object field that holds an empty string to null without having to iterate through

We have an object with values assigned but some of them are empty. Here is the object: { value1: 'bacon', value2: '', value3: 'lard', value4: '', value5: 'cheese', }; Can we transform ...

What is the best way to create a linear flow when chaining promises?

I am facing an issue with my flow, where I am utilizing promises to handle the process. Here is the scenario: The User clicks a button to retrieve their current position using Ionic geolocation, which returns the latitude and longitude. Next, I aim to dec ...

In TypeScript, how to refer to the type of the current class

Is there a way to reference the current class type in the type signature? This would allow me to implement something like the following: export class Component{ constructor(config?: { [field in keyof self]: any }) { Object.assign(this, config) ...

How can holidays be incorporated into the Kendo UI scheduler in Angular 6?

Is there a way to incorporate holidays into the Kendo UI scheduler in an Angular 6 project? I have a JSON array containing holiday dates, and during holidays I want to restrict users from adding events. Additionally, I would like the background color to b ...

Deactivate the rows within an Office UI Fabric React DetailsList

I've been attempting to selectively disable mouse click events on specific rows within an OUIF DetailsList, but I'm facing some challenges. I initially tried overriding the onRenderRow function and setting CheckboxVisibility to none, but the row ...

What steps can I take to avoid cross-project contamination within an Angular workspace?

Imagine having a project structured like this: projects |-app1 |-app2 |-common node_modules pakcage.json tsconfig.json angular.json ... (other root files) Currently, in a file within app1, you can have an import statement like this: import { Repository } ...

Encountering a Nuxt error where properties of null are being attempted to be read, specifically the 'addEventListener' property. As a result, both the default

Currently, I am utilizing nuxt.js along with vuesax as my UI framework. I made particular adjustments to my default.vue file located in the /layouts directory by incorporating a basic navbar template example from vuesax. Subsequently, I employed @nuxtjs/ ...

Chaining asynchronous HTTP requests in Angular 2: A guide to stopping execution if one request fails

I am faced with a challenge of executing an array of HTTP requests in a specific order, where if any request fails, the subsequent ones should not be executed. Is there a way to achieve this requirement? What would be the recommended approach to hand ...

Is it possible to utilize jwt tokens together with Firebase authentication?

Having previously built Spring Boot applications utilizing jwt tokens, Angular 7, and MySQL, I am now considering transitioning to Firebase solely for authentication purposes. Some tutorials suggest that Firebase can be directly implemented through Angular ...

Tips for sending a photo from Ionic's Camera to Firebase?

I recently used the Ionic camera API to capture an image successfully: async pickImage(sourceType: CameraSource) { const image = await Camera.getPhoto({ quality: 90, allowEditing: true, resultType: CameraResultType.Uri, source ...

Trying to access @PreAuthorize with the role 'ROLE_ADMIN' is resulting in a Forbidden error

When restricting access to a method for only admins, one can make use of @PreAuthorize("hasRole('ROLE_ADMIN')"). Below is an example implementation: @CrossOrigin(origins="http://localhost:4200") @RestController @RequestMapping("/api/v1") public ...

rxjs - straightforward issue with initiating observables

I'm currently tackling an assignment that involves setting up a basic form with input fields for 'From', 'To', and 'Duration' using rxjs. While it might be easier to just utilize getter / setters, I'm determined to ...

Should we utilize the component @Input as a parameter for the injected service constructor, or should we opt for the ServiceFactory

Within Angular 12 lies a simplified component structured as follows: @Component({ selector: 'app-list', templateUrl: './list.component.html', styleUrls: ['./list.component.less'] }) export class ListComponent implements ...