【发布时间】:2023-03-10 08:20:02
【问题描述】:
我目前正在尝试使用“BehaviorSubject”通过数据服务在组件之间发送数据。在第一个组件中,我正在更新 messageSoruce,在第二个组件中,我正在检索数据,但它是空的。我检查了值“this.card.img”不为空。我错过了什么?
数据服务
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)
}
}
【问题讨论】:
-
您是否意识到在您的第二个组件中您尝试设置
this.channe而不是this.channel? -
复制插入的时候出错了,值为this.channel
-
有什么方法可以创建堆栈闪电战或粘贴 html 模板。我要说一件事,就风格而言,使用 Observables 时的 Angular 约定是以
$结束变量名。因此,在您的 DataService 中,currentMessage应该是currentMessage$,除非您/您的组织不关心。 -
提供者:[DataServie] 只需要在 app.module.ts 中设置,就可以只使用一个实例。
标签: angular data-binding angular7 behaviorsubject data-sharing