【发布时间】:2017-05-15 20:36:32
【问题描述】:
我的应用程序是这样构建的:
- 我主要的一些基本组件(主页、登录、关于...) app.module
- 应用程序每个部分的一些其他模块
我有一个组件,ToastComponent,我可能需要在任何地方使用它。 我适用于基本组件,但不适用于模块中包含的组件。
我阅读了很多关于如何共享服务的页面,但是(我不明白我在 angular2 中承认的所有内容),我仍然无法弄清楚如何使其适用于我的情况。 (我什至尝试了一个共享模块,但它更糟)
我遇到的问题是给 setMessage 的消息(见代码末尾)显示在控制台中,但不在屏幕上!?!
希望有人能指出正确的编码方式。 TIA
日本
这是我恢复到已知阶段后的代码(经过多次尝试)......
Toast 组件:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-toast',
templateUrl: './toast.component.html',
styleUrls: ['./toast.component.css']
})
export class ToastComponent {
@Input() message = { body: '', type: '' };
setMessage(body, type, time = 5000) {
this.message.body = body;
this.message.type = type;
console.log('ToastComponent %o' , this.message);
setTimeout(() => { this.message.body = ''; }, time);
}
}
app.module
import { ToastComponent } from './_shared/toast.component';
...
import { LivresModule } from './livres/livres.module'; // where toast will be used
import { ExampleComponent } from './example.component'; // where toast is working fine
...
@NgModule({
imports: [ ... , LivresModule ],
providers: [ ToastComponent, ... ],
declarations: [ AppComponent, ToastComponent, ... ]
exports: [ ToastComponent ],
schemas: [ CUSTOM_ELEMENTS_SCHEMA ],
bootstrap: [ AppComponent ],
})
...
livres.module.ts
...
import { ToastComponent } from '../_shared/toast.component';
import { AuteursComponent } from './auteurs.component'; // where to use toast effectively
...
@NgModule({
...
providers: [ ToastComponent, ... ]
declarations: [
// ToastComponent, // error as declared twice with app.module : OK so commented
...
auteurs.component
...
import { ToastComponent } from '../_shared/toast.component';
...
constructor(private http: Http, private authorService: AuthorService,
private toast: ToastComponent ) { }
...
addAuthor() {
...
this.toast.setMessage('Auteur ajouté', 'success');
}
auteurs.component.html
...<app-toast [message]="toast.message"></app-toast>...
auteurs.component.* 是 app.module 的组件部分的副本,可以正常工作。
新信息: 我正在重新创建一个模仿我正在构建的轻量级应用程序,并且模块中的页面出现此错误:
Unhandled Promise rejection: Template parse errors:
Can't bind to 'message' since it isn't a known property of 'app-toast'.
1. If 'app-toast' is an Angular component and it has 'message' input, then verify that it is part of this module.
2. If 'app-toast' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
("<app-toast [ERROR ->][message]="toast.message"></app-toast>
<p> page2 works! </p>
<button (click)="displayMsg()"> Click !"): Page2Component@0:11
这就是我添加“模式:[CUSTOM_ELEMENTS_SCHEMA]”的原因(我已经忘记了),但实际上它隐藏了我在运行时遇到的编译时错误!
转换为服务不会带来 html 代码和 css。
【问题讨论】:
-
您谈论您遇到的错误,但您的问题中没有包含任何错误。请添加确切的错误消息。
-
完全没有错误:只有使用 setMessage 时没有出现在屏幕上的消息。
-
您需要将 Toast 代码设置为服务。请参阅此处以获得更好的实施:github.com/johnpapa/event-view
标签: angular components