嘿,如果登录失败,我试图在登录页面上显示一条简单的错误消息。以下是我的 login.component.html:
<div class="container shadow login-container">
<div class="row">
<div class="col-sm-12 text-center">
<div class="error-message">
<app-server-error [errorMessage]="error" ></app-server-error> -----> not displaying on screen
</div>
<div class="login-form-container">
<div class="login-input-container">
<input [(ngModel)]="user.email" type="email" placeholder="Enter your email" class="buddha-input"/>
</div>
<div class="login-input-container">
<input [(ngModel)]="user.password" type="password" placeholder="Enter password" class="buddha-input"/>
</div>
<div class="login-input-container">
<button (click)="tryLogin()" class="login-form-button">Login</button>
</div>
</div>
</div>
</div>
</div>
以下是我的 server-error.component.html:
<p>
{{errorMessage}}
</p>
以下是我的 server-error.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-server-error',
templateUrl: './server-error.component.html',
styleUrls: ['./server-error.component.css']
})
export class ServerErrorComponent implements OnInit {
@Input() public errorMessage: string;
constructor() { }
ngOnInit() {
}
}
“错误”未显示在屏幕上,控制台上也没有出现错误。请让我知道如何解决此问题?谢谢
答案 0 :(得分:1)
对于[errorMessage]="error"
,错误应该是一个变量。
因此您需要在组件中定义它。
但是,如果要显示字符串"error"
,
然后像这样[errorMessage]="'error'"
或errorMessage="error"
答案 1 :(得分:1)
@Input() public errorMessage: string;
期望error
是一个字符串。
在.ts中定义error
error = 'error message'
答案 2 :(得分:-1)
其他发布的答案可能会解决您的问题,但我会选择与Service一起使用,该服务将负责显示应用程序中各处的错误,并且您可以完全控制错误组件,例如它集中在一个地方:
错误服务:
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class ErrorService {
constructor() { }
private errorMessages = new BehaviorSubject('');
errorMessage = this.errorMessages.asObservable();
showError(message: string) {
this.errorMessages.next(message)
}
}
Error.Component.ts:
import { Component, OnInit, Input } from '@angular/core';
import {ErrorService } from "../error.service";
@Component({
selector: 'app-server-error',
templateUrl: './server-error.component.html',
styleUrls: ['./server-error.component.css']
})
export class ServerErrorComponent implements OnInit {
private errorMessage : any;
constructor(public errorService : ErrorService) { }
ngOnInit() {
this.errorService.errorMessage.subscribe(value => {
this.errorMessage = value;
})
}
}
App.Component.html:
// show it in app.component
<div class="error-message">
<app-server-error></app-server-error>
</div>
使用(在登录组件中):
import { Component, OnInit } from "@angular/core";
import {ErrorService } from "../error.service";
@Component({
selector: "app-login",
templateUrl: "./login.component.html",
styleUrls: ["./login.component.css"]
})
export class LoginComponent implements OnInit {
constructor(public errorService: ErrorService) {}
user = {};
ngOnInit() {}
tryLogin(){
this.errorService.showError('An error');
}
}