用EventEmitter实现订阅功能,调试代码时可以正常接收,但是页面上不显示,这是为什么?
调试
html
结果
代码如下:
service:
import {EventEmitter, Injectable} from '@angular/core';
export class Book {
name: string;
price: number;
}
@Injectable()
export class BookService {
bookEventer: EventEmitter<Book> = new EventEmitter();
}
emit
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css'],
encapsulation: ViewEncapsulation.None
})
export class HomeComponent implements OnInit, OnDestroy {
book: Book;
constructor(private bookService: BookService) {
}
ngOnInit() {
this.book = {name: '《万历十五年》', price: 10.0};
}
ngOnDestroy() {
this.bookService.bookEventer.emit(this.book);
}
}
subscribe
import {Component, OnInit, ViewEncapsulation} from '@angular/core';
import {Book, BookService} from './book';
@Component({
selector: 'app-book',
templateUrl: './book.component.html',
styleUrls: ['./book.component.css'],
encapsulation: ViewEncapsulation.None
})
export class BookComponent implements OnInit {
protected subscribeBook: Book;
constructor(private bookService: BookService) {
}
ngOnInit() {
this.bookService.bookEventer.subscribe(book => {
this.subscribeBook = book;
});
}
}
路由配置
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import {HomeComponent} from './home/home.component';
import {BookComponent} from './book/book.component';
const routes: Routes = [{path: '', component: HomeComponent}, {path: 'books', component: BookComponent}];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
自己解决。在service中定义一个临时变量来供传递即可。