Issue with subscribing in a MEAN stack application

Currently, I have completed the backend development of my application and am now working on the frontend. My focus at the moment is on implementing the register component within my application.

Below is the code snippet for my Register Component where I am trying to register a user. The issue I'm facing is that although the OnRegisterSubmit method successfully creates and writes the user data to the database, the remaining code doesn't seem to work as expected, leading me to suspect that the .subscribe() method may not be functioning correctly.

export class RegisterComponent implements OnInit {

  username: String | null = null;
  password: String | null = null;
  firstname: String | null = null;
  lastname: String | null = null;

  constructor(private validateService: ValidateService,
              private authService: AuthService,
              private router: Router
          ){}

  ngOnInit(){}

  onRegisterSubmit(){
    const user = {
      username: this.username,
      password: this.password,
      firstname: this.firstname,
      lastname: this.lastname
    }

    if(!this.validateService.validateRegister(user)){
        alert('Please fill in all fields');
        return;
    }

   //Register User
   this.authService.registerUser(user).subscribe(data => {
    if((data as any).success ) {
      // Registration was successful
      alert('You are now registered');
      this.router.navigate(['/login']);
    } else {
      // Registration failed
      alert('Something went wrong');
      this.router.navigate(['/register']);
    }
  });

  return null;
  
  }
}

The following is my auth.service:

interface User {
  username: String | null;
  password: String | null;
  firstname: String | null;
  lastname: String | null;
}

@Injectable({
  providedIn: 'root'
})
export class AuthService {

  authToken: any;

  constructor(private httpClient: HttpClient) { }

  registerUser(user: User) {
    const headers = new HttpHeaders().set('Content-Type', 'application/json');
    return this.httpClient.post('https://localhost:3000/api/users/signup', user, { headers });
  }
  
}

Lastly, here's my user route implementation:

// Create new user
router.post('/signup', async(req,res) => {
    const {error} = validateUser(req.body);
    if (error) return res.status(400).json(error.details[0].message);

    const isUnique = (await User.count({username: req.body.username})) === 0;
    if(!isUnique)
    return res
.status(401)
.json({error: 'The username or password is not valid'});
try{
    const user = new User(req.body);
    user.password=await hashPassword(user.password);
    await user.save();
} catch(err) {
    return res.status(500).json(err);
}
res.status(200);
})

If anyone has insights into why this issue is occurring, your assistance would be greatly appreciated. Thank you.

If additional information is required, please feel free to inquire.

Answer №1

Give this a shot:

.observe({
    then: (value) => print(value),
    problem: (issue) => report(issue),
    finished: () => notify('finished')
})

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

Track the loading time of a webpage and the time it takes to render all subelements of

For my project, I need to track page load times for each individual visitor. My idea is to embed a JavaScript snippet into the page in order to achieve this goal. However, the task is more complex than I anticipated because I also need to measure the respo ...

In JavaScript with Node.js, how can one verify a file's size and only download the initial kilobyte of the file?

When using Javascript/Node JS to download a file, you can check the file size and download only the first kilobyte of the file. This is useful if you want to hash the first kb and compare it with the hash of the complete file. If the hashes match and the ...

When attempting to install an npm package using npm link, you may encounter the error TS2307: Module not found

I'm in the process of developing an Angular library called clan-auth that will contain shared components for multiple Angular projects. When I install the library from our private npm Repository, everything works as expected. However, when I try to li ...

Can Angular Universal be configured to have all HTTP Requests originate from the Server instead of the Client's Browser in an Angular Application?

With specific requirements in mind, I require the Angular application to carry out all requests on the server rather than on the client's browser. After implementing SSR (Server-Side Rendering) through Angular Universal on my application, I anticipat ...

Code not functioning properly in Internet Explorer

In one of my JavaScript functions, I have the following CSS line which works well in all browsers except for IE (Internet Explorer). When the page loads, the height of the element is only about 4px. element.setAttribute('style', "height: 15px;") ...

What could be the reason for the malfunctioning of my React Native vector icons?

My react native vector icons are not working despite following all the steps mentioned in the documentation. I am unable to use a camera icon in my app. I tried importing { Entypo } from 'react-native-vector-icons'; and then using \<Entyp ...

Tips for implementing HTML5 validation followed by automatic redirection to a different page

I'm new to web development and struggling with how to make a button both validate inputs and redirect to another page. Using the onclick = "" function, I can validate inputs like emails and telephone numbers, but I'm having trouble making it so t ...

Avoiding hydration errors when using localStorage with Next.js

Want to save a token and access it using local storage The code snippet I am using is: if (typeof window !== 'undefined') { localStorage.setItem(key, value) } If I remove the window type check, I encounter this error: localStorage is not ...

Is there a way to display two words side by side in React components?

I previously had the following code: projectName: project.get('name') === 'default' ? 'No Project' : project.get('name') In the render() method, it was written like this: <div className='c-card__projects&ap ...

Ways to showcase an item within additional items?

I'm struggling to properly display data in a table. My goal is to iterate through an object within another object inside an array and showcase the source, accountId, name, and sourceId in the table. https://i.sstatic.net/VVIuc.png <tbody clas ...

How to Toggle Visibility of Angular2 Material Drop Down Menu?

My Code <mat-form-field class="button-spacing"> <mat-select placeholder="select" [(ngModel)]="dropDownOne"> <mat-option *ngFor="let first of test1" [value]="first"> {{ first }} </mat-option> </mat-select> </mat-fo ...

The function of the Angular ng-include form action for posting a URL appears to be malfunctioning

When a form post is included in a parent HTML using ng-include, it does not trigger the submission action. <div ng-include src="'form.html'"></div> The code in the form.html file is as follows: <form action="next/login" method = ...

"Exploring the TypeScript typing system with a focus on the typeof operator

My goal is to create a function that will return the typeof React Component, requiring it to adhere to a specific props interface. The function should return a type rather than an instance of that type. Consider the following: interface INameProps { ...

When there are numerous websocket connections in Google Chrome, Socket.io can encounter issues and break down

I am encountering an issue where I create 60 client connections to a socket.io server using Google Chrome browser. The server sends screenshots to the clients at specific times, but some of the websocket connections, which are subprotocols of socket.io, ge ...

Encountering the "EHOSTUNREACH" error message while attempting to establish a connection to an API through the combination of Axios and Express

Exploring the capabilities of the Philips Hue Bridge API, I delved into sending requests using Postman. To my delight, I successfully authenticated myself, created a user, and managed to toggle lights on and off. Verdict: Accessing the API is achievable. ...

Developing a dynamic web application using the Django framework along with the Vue.js library and Highcharts for

I am currently working on a data visualization web app using Django, Highcharts, and JQuery. I have recently transitioned from JQuery to Vue JS and I am struggling with fetching JSON data from a specific URL. Below is the code snippet: Template <!doc ...

What is causing the issue with transmitting the server datetime to my local jQuery script?

I am facing an issue with my timeoftheserver.php page setup. The PHP code is quite simple: <?php echo date('D, d M y H:i:s'); ?> Similarly, the script on my local machine is also straightforward: var today; try { today = new Date($. ...

Inspecting a union type with a TypeScript property validation

I have defined a union of two types in my code. Here are the definitions: type Generic = { subtype: undefined, user: string, text: string } type Other = { subtype:'message', text: string } type Message = Generic | Other; Within my co ...

Async Laziness Loading

At the moment, our team is utilizing the SAP HANA Database for data storage. We plan to retrieve this data using a Node.JS-API through AJAX calls in order to take advantage of asynchronous processing. However, we have encountered a challenge: Across multi ...

Connecting Angular modules via npm link is a great way to share common

Creating a project with a shared module that contains generic elements and components, such as a header, is my goal. This shared module will eventually be added as a dependency in package.json and installed through Nexus. However, during the development ph ...