0

i keep getting this error on angular 6 have codes the backend now on connecting on registering the user he should be directed to the admin dashboard unfortunately am getting that caoont be read the property of success is null while when i use another route the pop up window tells me undefined hellp me guys am to submit this assignment on Wednesday am newbie from tanzania

core.js:6014 ERROR TypeError: Cannot read property 'success' of null
    at SafeSubscriber._next (login.component.ts:26)

Show 40 more framesHere is my login.components.ts```

Here is my login.components

import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/auth.service';
import { Router } from '@angular/router';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {

  constructor(private Auth: AuthService,private router: Router) { }

  ngOnInit() {
  }
  loginUser(event)
  {
    event.preventDefault()
    const target = event.target
    const email= target.querySelector('#email').value
    const password = target.querySelector('#password').value


    this.Auth.loginUser(email, password).subscribe(data => {
      if(data.success)
      {
        //redirect the person to admin page
        this.router.navigate(['admindashboard'])
        this.Auth.setLoggedIn(true)


      }
      else
      {
        window.alert(data.message)
      }
      return false;
    });
    console.log(email, password)
  }

}```

here is my auth.service.ts

import { Injectable } from '@angular/core';
import{ HttpClient } from '@angular/common/http';

interface myData
{
  success:boolean,
  message: string
}

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  uri ='http://localhost:4000';

  private loggedInStatus = false
  constructor(private http: HttpClient) { }

  setLoggedIn(value: boolean)
  {
  this.loggedInStatus = value
  }

  get isLoggedIn()
  {
    return this.loggedInStatus
  }


  loginUser(email,password){
    return this.http.post<myData>(`${this.uri}/register`, {
      email,
      password
    });
  }


}```

Here is my Api

``` server.post('/register', (req, res, next) => {


     const { email, password } = req.body;

     const clearadmin = new Clearadmin({
         email,
         password
     });

     bcrypt.genSalt(10, (err, salt) => {

        bcrypt.hash(clearadmin.password, salt, async (err, hash) => {

            //Hash Password
            clearadmin.password = hash;

            //save clearadmin
            try{
               const newClearadmin = await clearadmin.save();
               res.send(201);
               next();
            }
            catch(err)
            {
             return next(new errors.InternalError(err.message));
            }
        });
     });
    });```

My ClearAdmin Mongoose Schema


const ClearAdminSchema = new mongoose.Schema({
    email:
    {
        type:String,
        required:true,
        trim:true
    },
    password:{
        type:String,
        required:true
    }
});

const ClearAdmin = mongoose.model('ClearAdmin', ClearAdminSchema);
module.exports = ClearAdmin;```

    *the new Error am getting n my console now*

    ```Server started on port 4000
    (node:921) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot render headers after they are sent to the client
        at ServerResponse.writeHead (_http_server.js:236:13)
        at ServerResponse.restifyWriteHead [as writeHead] (/Users/retina/ocapp/node_modules/restify/lib/response.js:632:25)
        at flush (/Users/retina/ocapp/node_modules/restify/lib/response.js:849:9)
        at ServerResponse.__send (/Users/retina/ocapp/node_modules/restify/lib/response.js:431:24)
        at ServerResponse.send (/Users/retina/ocapp/node_modules/restify/lib/response.js:316:21)
        at bcrypt.hash (/Users/retina/ocapp/routes/clearadmins.js:42:21)
        at process._tickCallback (internal/process/next_tick.js:68:7)
    (node:921) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
    (node:921) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.```


Kyle Mutta
  • 379
  • 1
  • 5
  • 16

1 Answers1

1

Firstly, you are not sending the user credentials the right way, email & password should be sent as a key-value JSON object in your service auth.service.ts. like this

loginUser(email,password){
    return this.http.post<myData>(`${this.uri}/register`, {
      email:email,
      password:password
    });
  }

Next, In your component login.component.ts you are trying to read the success property, while in your API, your response does not contain this property. Your API response should look like this.

res.status(201).json({
                        success:true,
                        msg:'registration successful'
                    })

And, In your API, I would suggest you to read the email & password in this way

const email = req.body.email;
const password = req.body.password;

Replace this

const clearadmin = new Clearadmin({
         email,
         password
     });

With this

const clearadmin = new Clearadmin({
         email:email,
         password:password
     });

Add the save method to your mongoose model, like this

const ClearAdminSchema = new mongoose.Schema({
    email:
    {
        type:String,
        required:true,
        trim:true
    },
    password:{
        type:String,
        required:true
    }
});

const ClearAdmin = modules.exports = mongoose.model('ClearAdmin', ClearAdminSchema);
//Save the user
module.exports.saveUser = function(newUser, callback){
    newUser.save(callback);
}

Now, make changes to your register route

server.post('/register', (req, res, next) => {

     const email = req.body.email;
     const password = req.body.password;

     const clearadmin = new Clearadmin({
         email:email,
         password:password
     });

     bcrypt.genSalt(10, (err, salt) => {

        bcrypt.hash(clearadmin.password, salt, async (err, hash) => {

            //Hash Password
            clearadmin.password = hash;

            //save clearadmin
            Clearadmin.saveUser(clearadmin,(err,registered)=>{
              if(err){
                  res.json({success:false, msg:'Error occurred at backend'})
              }if(registered){
                  res.json({success:true, msg:'user registered'})
              }
            })
        });
     });
    });
Shivam Gautam
  • 31
  • 2
  • 8
  • Thanks men but now am getting a pop up saying localhost:4200 says undefined – Kyle Mutta Oct 15 '19 at 07:37
  • In your login.component.ts make changes to `window.alert(data.msg)` to read the msg property returned from backend and in your API return the json object with 'msg' for error in your catch block as well. Let me know if you don't know how to do that – Shivam Gautam Oct 15 '19 at 08:08
  • Here is how your catch block should look like `catch(err){res.status(500).json({success:false,msg:'Failed to register'})}` – Shivam Gautam Oct 15 '19 at 08:12
  • By doing this, if you receive a success:false, you will know that something is wrong with your API only and your Angular Front-end is good. If that's the case, I need to see more of your API code & what DB you are using. – Shivam Gautam Oct 15 '19 at 08:16
  • thanks men i did now get my erros its says that UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot render headers after they are sent to the client please help me with this too – Kyle Mutta Oct 15 '19 at 08:22
  • my api is up there am using mongoose db – Kyle Mutta Oct 15 '19 at 08:23
  • Check the updated answer. If still there are errors, I need to see your Clearadmin mongoose model – Shivam Gautam Oct 15 '19 at 08:29
  • i have just added it on the above question please check it out – Kyle Mutta Oct 15 '19 at 08:33
  • but when i check the database it adds the new registred user the problem is it cant navigate to admindashboard – Kyle Mutta Oct 15 '19 at 08:37
  • yes here is the error UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot render headers after they are sent to the client – Kyle Mutta Oct 15 '19 at 08:41
  • check the edit, I have created a save method in the mongoose model file and called that method from your register route. I have also removed the try catch with much elegant if else code – Shivam Gautam Oct 15 '19 at 08:58
  • Let me know, if still there are any errors. If it resolves your issue, kindly mark this answer as accepted – Shivam Gautam Oct 15 '19 at 09:19
  • am getting this error now TypeError: Clearadmin is not a constructor const clearadmin = new Clearadmin({ – Kyle Mutta Oct 15 '19 at 12:19
  • have you imported your mongoose model file? eg. `const Clearadmin = require('path_to_models/clearadmin_model.js')` – Shivam Gautam Oct 15 '19 at 16:08
  • yes i did check up the question i have posted all the errors showing in my console – Kyle Mutta Oct 15 '19 at 16:48