在组件之间共享数据(Angular 7) [英] Sharing Data between Components (Angular 7)

查看:32
本文介绍了在组件之间共享数据(Angular 7)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试使用BehaviorSubject"通过数据服务在组件之间发送数据.在第一个组件中,我正在更新 messageSoruce 并在第二个组件中检索数据但它是空的.我检查了值this.card.img"不为空.我错过了什么?

I am currently trying to send data between components via a data service using "BehaviorSubject". In the first component, I am updating the messageSoruce and in the second component , retrieving the data but it is empty. I checked that the value "this.card.img" is not empty. What am I missing ?

数据服务

import { Injectable } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';


@Injectable()
export class DataService {

private messageSource = new BehaviorSubject("")
currentMessage = this.messageSource.asObservable();

constructor() { }

  changeMessage(message: string) {
  this.messageSource.next(message)
    }

 }

第一个组件

import {Component} from '@angular/core';
import {Router} from '@angular/router';
import {DataService} from 'src/app/services/data/data.service';


@Component({
  selector: 'app-card',
  templateUrl: './card.component.html',
  providers: [ DataService ],
  styleUrls: ['./card.component.css']
})


export class CardComponent {



  @Input('card') card:Card 


  constructor(public router: Router,
              public dataService :DataService ) {

  }

  openDetails() {

   this.dataService.changeMessage(this.card.img)
   this.router.navigateByUrl('/imganalyse');

  }

}

第二部分

import { Component, OnInit, } from '@angular/core';
import {DataService} from '../../services/data/data.service'

@Component({
  selector: 'app-imganalyse',
  templateUrl: './imganalyse.component.html',
  providers: [ DataService ],
  styleUrls: ['./imganalyse.component.css']
})



export class ImganalyseComponent implements OnInit {

  channel: string;

  constructor(private  youtubeService:YoutubeService,
              private dataService:DataService) { 

  }

  ngOnInit() {

  this.dataService.currentMessage.subscribe(channel => this.channel = channel)


  console.log(this.channel)

  }

}

推荐答案

解决方案:

提供者:[DataServie] 只需要在 app.module.ts 中设置就可以只使用一个实例.在我的情况下,每个组件都有自己的数据服务提供者,因此它有多个实例......(这就是它始终为空的原因)

The providers: [DataServie] needs only to be set in app.module.ts to only use one instance. In my case every component had his own dataservice provider , therefore it had more than one instance ...(that's the reason why it was always empty)

这篇关于在组件之间共享数据(Angular 7)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆