0
import { Component, OnInit, Injectable} from '@angular/core';
import {Http, Response} from '@angular/http';
import { GuessService } from './guess.service';
import 'rxjs/add/operator/map';
import {Router} from '@angular/router';

declare var jQuery:any;
declare var $ :any;

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

  constructor(private router: Router) {}

  ngOnInit() {


  }
  CheckLogin(name,pass)
  {

    $.ajax({
      headers:{  

   "Accept":"application/json",//depends on your api
    "Content-type":"application/x-www-form-urlencoded"//depends on your api
      },   url:"http://199.188.207.196:5555/user/login/",
      method:"post",
      data:{"email":name,"password":pass},
      success:function(response){

        if(response.success == true){
        console.log("ok");
        this.router.navigate(['/main']);
      }
        else{
          console.log("backend");
        }
      }
    });
  }    

}

When user click on CheckLogin button then it must route to login component, but in my side it show error.

I found solution of my question in stackoverflow but it's not working, i don't know what is the problem.

11
  • Post your template and whole component code Commented Jan 12, 2018 at 14:09
  • Its just a class , not even a component. Please post whole code Commented Jan 12, 2018 at 14:11
  • Is the router declared in the module? Commented Jan 12, 2018 at 14:12
  • I have added whole component Commented Jan 12, 2018 at 14:13
  • 1
    You have lost the context of this, is there a reason you are using jQuery ajax instead of Angular HttpModule? Commented Jan 12, 2018 at 14:26

2 Answers 2

1

you need to add => so that you can have the reference to the component.
e.g :

CheckLogin(name,pass) => {  
...  
} 

this answer here was a pointer for me, it is still like a hack, you need to do things properly.
Angular2 injected Router is undefined

Sign up to request clarification or add additional context in comments.

2 Comments

you mean like this CheckLogin = (name,pass) => {...}
Yes,using arrow functions, should be something like: CheckLogin = (name,pass) => { ... }
0

Try this

import { Component, OnInit, Injectable} from '@angular/core';
import {Router, ActivatedRoute} from '@angular/router';

export class GuessComponent implements OnInit {

constructor(private router: Router, private route: ActivatedRoute) {}

CheckLogin(name,pass)
{
  this.router.navigate(['/login'], {relativeTo: this.route});
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.