我正在开发一个 springboot/angular(版本 11.2.7)应用程序。我想在启动时显示登录页面
这是 index.html 页面
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Frontend</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>
这是登录组件
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import {LoginService} from "./login.service";
@Component({
selector: 'app-root',
templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
public formGroup: FormGroup;
public error: boolean = false;
private credentials = {username: '', password: ''};
constructor(private formBuilder: FormBuilder, private loginService: LoginService, private http: HttpClient, private router: Router) {
}
ngOnInit() {
this.formGroup = this.formBuilder.group({
username: ['', Validators.compose([Validators.email, Validators.required])],
password: ['', Validators.compose([Validators.required])]
});
}
login() {
this.credentials.username = this.formGroup.get('username').value;
this.credentials.password = this.formGroup.get('password').value;
this.loginService.authenticate(this.credentials, () => {
this.router.navigateByUrl('/homepage');
});
return false;
}
}
这是 app.module.ts 文件
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { LoginComponent } from './login/login.component'
import { AppComponent } from './app.component';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { HttpsInterceptor } from './http.interceptor';
import {ReactiveFormsModule} from "@angular/forms";
@NgModule({
declarations: [
AppComponent,
LoginComponent
],
imports: [
BrowserModule,
HttpClientModule,
ReactiveFormsModule,
AppRoutingModule
],
providers: [{ provide: HTTP_INTERCEPTORS, useClass: HttpsInterceptor, multi: true } ],
bootstrap: [LoginComponent]
})
export class AppModule { }
这是 AppRoutingModule
import { Routes, RouterModule } from '@angular/router';
import {LoginComponent} from "./login/login.component";
import {NgModule} from "@angular/core";
const routes: Routes = [
{
path: '',
redirectTo: '/login',
pathMatch: 'full'
},
{
path: 'login',
component: LoginComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes,
{ enableTracing: false })],
exports: [RouterModule]
})
export class AppRoutingModule { }
这是 Spring 控制器
package com.example.commission.controllers;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Collections;
import java.util.Map;
@RestController
// we allow localhost:4200 for testing purposes
@CrossOrigin(origins = "http://localhost:4200")
public class HelloController {
@RequestMapping(value = "/message", produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, String> index() {
return Collections.singletonMap("message", "Greetings from Spring Boot!");
}
}
但是当我浏览 http://localhost:8080/ 时,控制台中出现错误信息
ERROR Error: The selector "ng-component" did not match any elements
Angular 24
selectRootElement
locateHostElement
create
bootstrap
_moduleDoBootstrap
_moduleDoBootstrap
bootstrapModuleFactory
invoke
onInvoke
invoke
run
scheduleResolveOrReject
invokeTask
onInvokeTask
invokeTask
runTask
drainMicroTaskQueue
promise callback*scheduleMicroTask
scheduleTask
scheduleTask
scheduleMicroTask
scheduleResolveOrReject
then
bootstrapModule
zUnb main.ts:11
Webpack 6
__webpack_require__
0
__webpack_require__
checkDeferredModules
webpackJsonpCallback
<anonymous>
我更改了以下内容
bootstrap: [AppComponent]
})
export class AppModule { }
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
providers: [HttpClient]
})
export class AppComponent implements OnInit{
@Component({
selector: 'app-login',
templateUrl: './login.component.html'
})
export class LoginComponent implements OnInit {
和 app.component.html
<div class="jumbotron">
<div class="container">
<div class="row">
<div class="col-sm-6 offset-sm-3">
<router-outlet></router-outlet>
</div>
</div>
</div>
我改变了路由
const routes: Routes = [
{ path: '', component: HomeComponent, canActivate: [AuthGuard] },
{ path: 'login', component: LoginComponent },
// otherwise redirect to home
{ path: '**', redirectTo: '' }
];
@NgModule({
imports: [RouterModule.forRoot(routes,
{ enableTracing: false })],
exports: [RouterModule]
})
export class AppRoutingModule { }
为了增量目的 AuthGuard 返回 false 并重定向到登录页面
import { Injectable } from '@angular/core';
import { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
//import { AuthenticationService } from '@app/_services';
@Injectable({ providedIn: 'root' })
export class AuthGuard implements CanActivate {
constructor(
private router: Router
//,private authenticationService: AuthenticationService
) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
/* const currentUser = this.authenticationService.currentUserValue;
if (currentUser) {
// logged in so return true
return true;
}*/
// not logged in so redirect to login page with the return url
this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });
return false;
}
}
答案 0 :(得分:0)
我进步了
这是我的项目结构
- PorjectName
- backend
......
pom.xml
- frontend
.......
pom.xml
- pom.xml
当我从 ProjectName 运行 mvn clean package 然后从前端目录运行 ng serve 时,错误消失了。为什么?
这里是前端模块的pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<groupId>dev.xavier</groupId>
<artifactId>java-angular-commission</artifactId>
<version>0.1-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>frontend</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
<type>maven-plugin</type>
</dependency>
</dependencies>
<build>
<plugins>
<!-- clean the dist directory used by Angular -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<filesets>
<fileset>
<directory>dist</directory>
</fileset>
</filesets>
</configuration>
</plugin>
<plugin>
<groupId>com.github.eirslett</groupId>
<artifactId>frontend-maven-plugin</artifactId>
<version>1.11.2</version>
<executions>
<!-- Install node and npm -->
<execution>
<id>Install Node and NPM</id>
<goals>
<goal>install-node-and-npm</goal>
</goals>
<configuration>
<nodeVersion>v14.16.0</nodeVersion>
</configuration>
</execution>
<!-- clean install -->
<execution>
<id>npm install</id>
<goals>
<goal>npm</goal>
</goals>
</execution>
<!-- code validation -->
<!-- <execution>
<id>npm run lint</id>
<goals>
<goal>npm</goal>
</goals>
<phase>test</phase>
<configuration>
<arguments>run lint</arguments>
</configuration>
</execution>-->
<!-- build app -->
<execution>
<id>npm run build</id>
<goals>
<goal>npm</goal>
</goals>
<configuration>
<arguments>run build --prod</arguments>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
<resources>
<resource>
<!-- we copy the content of the frontend directory in the final artifact -->
<directory>dist/frontend</directory>
</resource>
</resources>
</build>
</project>