在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/HTML5/ angular訂閱的值在頁面上不顯示?

angular訂閱的值在頁面上不顯示?

用EventEmitter實(shí)現(xiàn)訂閱功能,調(diào)試代碼時(shí)可以正常接收,但是頁面上不顯示,這是為什么?

調(diào)試
clipboard.png

html

clipboard.png

結(jié)果

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 { }
回答
編輯回答
傲嬌范

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

2018年8月30日 03:18
編輯回答
笨笨噠

自己解決。在service中定義一個(gè)臨時(shí)變量來供傳遞即可。

2018年5月31日 05:01