3

I am trying to connect my angular 6 application with sprint boot 2 web application. But I am unable to connect. I've added CrossOrigin in controller but the connection is not going to the controller. I also tried adding url in proxy.confg.json file but its not working.

here is my app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { ClienthomepageComponent } from './clienthomepage/clienthomepage.component';
import { AddclientComponent } from './addclient/addclient.component';
import { HeadermappingComponent } from './headermapping/headermapping.component';

//import { Http, Response } from "@angular/http";
//import { HttpClient, HttpHeaders } from '@angular/common/http';

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

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    ClienthomepageComponent,
    AddclientComponent,
    HeadermappingComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule,
//    Http,
//    HttpClient,
    RouterModule.forRoot([
        {
            path: '',
            component: LoginComponent
        },
        {
            path: 'clientslist',
            component: ClienthomepageComponent
        },
        {
            path: 'addClient',
            component: AddclientComponent
        }
    ]),
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

login.component.html

<div class="container pt-5 mt-5">
    <div class="col-lg-12">
        <div class="row d-flex justify-content-center">
            <form (submit)="checkUser($event)">
                <div class="col-md-10" id='login-wrap'>
                    <div class="retailmodal">
                        <div class="modal-content">
                            <div class="modal-body d-flex justify-content-center" id="firstFrom">
                                <div class="row d-flex justify-content-center">
                                    <div class="col-12"><input type="text" placeholder="UserName" id = "username"></div>
                                    <div class="col-12"><input type="password" placeholder="Password" id = "password"></div>
                                    <div class="col-12 "><input type="submit" value="Login"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </form>
            <div class="col-md-12" style="clear:both;height:40px;"></div>

            <div class="col-lg-2"></div>
        </div>
    </div>
</div>

login.component.ts

import { Component, OnInit } from '@angular/core';
import {LoginService} from '../login.service';

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

  constructor(private loginService: LoginService) { }

  ngOnInit() {

  }
  checkUser(event){
    event.preventDefault()
    const target = event.target;
    const userName = target.querySelector('#username').value;
    const password = target.querySelector('#password').value;

    console.log(userName, password);
    this.loginService.checkUsers();
//    this.loginService.findClientByNameAndPwd(userName,password);
}

}

login.service.ts

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Http, Response } from "@angular/http";
@Injectable({
  providedIn: 'root'
})
export class LoginService {
 private baseUrl = 'http://localhost:8084/login';
    private apiUrl = '/api/employees';
  constructor(private http:HttpClient) { 
  }
  checkUsers(): Observable<any> {
      console.log(`${this.baseUrl}`);
    return this.http.get(this.baseUrl);
  }
  findClientByNameAndPwd(username: string,password:string): Observable<any> {
      console.log(`login/username/${username}/password/${password}`);
//    return this.http.get(`login/username/${username}/password/${password}`);
      return this.http.get(this.apiUrl)
  }

//   public checkUsers() {
//    return this.http(this.baseUrl);
//  }

}

LoginController.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 *
 * @author xyz
 */
@RestController
//@RequestMapping("/api")
public class LoginController {
    @GetMapping("/login")
    @CrossOrigin(origins = "http://localhost:4200")
    public String loginPage(){
    System.out.print("");

    return "";
    }
}

EmailreportsApplication.java

package com.xyx.emailreports;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication(scanBasePackages = {"com.netelixir"} )
@EnableAutoConfiguration
@ComponentScan
public class EmailreportsApplication extends SpringBootServletInitializer{

    public static void main(String[] args) {
        SpringApplication.run(EmailreportsApplication.class, args);
    }
         @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
    return application.sources(EmailreportsApplication.class);
  }
}
18
  • 1
    Is your Spring boot application at the root level of package? Commented Aug 2, 2018 at 9:25
  • angular project and spring boot project are separate. Spring boot project running in tomcat server localhost:8084 and angular project at localhost:4200 Commented Aug 2, 2018 at 9:35
  • Correct. there must be a file with @SpringBootApplication annotation. Is that file in the same package as your controller? Commented Aug 2, 2018 at 9:36
  • no both are in different package Commented Aug 2, 2018 at 9:37
  • Okay, the file with spring boot annotation has to be at a root level package. Can you post that file too? It would be easier to explain then. Commented Aug 2, 2018 at 9:38

1 Answer 1

1

The http - service needs a subscriber

your service:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class LoginService {
   private baseUrl = 'http://localhost:8084/login';
   private apiUrl = '/api/employees';

  constructor(private http:HttpClient) { }

  checkUsers()
  {
    return this.http.get(this.baseUrl);
  }
  ...
}

login component:

....

this.loginService.checkUsers().subscribe();

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

1 Comment

Yes you must use .subscribe(). Please refers to angular.io httpClient docs to more nformations.

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.