angular订阅的值在页面上不显示?

用EventEmitter实现订阅功能,调试代码时可以正常接收,但是页面上不显示,这是为什么?

调试
clipboard.png

html

clipboard.png

结果

clipboard.png

代码如下:

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 { }
阅读 3.2k
2 个回答

自己解决。在service中定义一个临时变量来供传递即可。

html中写成{{subscribeBook.name}}就可以了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏