在具有主题行为的组件之间传递数据并不适用于路由

时间:2017-12-02 11:32:24

标签: angular angular-cli

我有两个组件都被路由

1.登录和家庭组件

我在主题行为的帮助下将数据从登录传递到家。我从登录页面发送到主页的数据不成功。请查看我在stackblitz上的code

Here is components
// Login component

import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { MessageService } from './../../message.service';

@Component({
  selector: 'login',
  template: `
    <h1>Login</h1>
    <button (click)="newMessage()">send message to subject behaviour</button>
  `,
})
export class LoginViewComponent {
  constructor(private messageService: MessageService) {}
  newMessage() {
    this.messageService.nextMessage({'style_number': 21,
    'product_id': 23, 'vendor_id': 44});
  }
}

// Home component
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { MessageService } from './../../message.service';

@Component({
  selector: 'home',
  template: `
    <div>
      <h1>Home</h1>
      <h3>Total users: # {{users?.length}}</h3>
    </div>
    <button (click)="newMessage()">send message to subject behaviour</button>
  `,
})
export class HomeViewComponent {

  users;

  constructor(private http: Http, private messageService: MessageService) {
    this.http.get('https://jsonplaceholder.typicode.com/users')
      .map(res => res.json())
      .subscribe(res => this.users = res)
  }
  ngOnInit() {
    this.messageService.currentMessage.subscribe(message => {
      console.log('message received', message);
    });
  }
  newMessage() {
    this.messageService.nextMessage({'style_number': 21,
    'product_id': 23, 'vendor_id': 44});
  }
}

screenshot

如果有人点击登录页面上的按钮,我需要在主页中立即查看数据

0 个答案:

没有答案