【问题标题】:Send data from one componentA to componentB on clicking at a place in componentA (through angular service)单击组件A中的某个位置(通过角度服务)将数据从一个组件发送到组件
【发布时间】:2021-07-08 07:20:39
【问题描述】:

我正在开发一个简单的音乐应用程序。现在在应用程序中,我有两个组件,一个是包含音频播放器(即音量条、搜索栏、播放暂停等)的主组件 A,另一个是包含所有歌曲的组件 B。

我的目标是,每当有人点击组件 B(即歌曲列表)上的歌曲时,该歌曲的详细信息(url、img 等)就会立即发送到组件 A,以便歌曲开始播放。

这是我的 componentB.html

<div *ngFor="let song of songs | filter:searchText" 
      (click)="songSelected(song.url,song.name)">
      <img src="{{song.img}}">
      <div>
        <p><strong>{{song.name}}</strong><br>
        <h6>{{song.singer}}</h6>
      </div>
    </div>

songSelected() 上面的工作正常。

这是我的componentB.ts

  songSelected(url: string,name:string){
      this.selectedurl=url
      this.selectedname=name
      this._allsongs.setData(this.selectedurl,this.selectedname);
      
  }
  constructor(public _allsongs:AllsongsService) { }

  ngOnInit(): void {
    this.songs=this._allsongs.getSongs();
  }

这是我的service.ts

setData(url: any, name: any) {
    console.log("From Service set data previous = " + this.name)
    this.url = url;
    this.name = name;
    console.log("From Service set data new = " + this.name)
  }

  getData(): any {
    return [this.url, this.name]
    
  }

这是我的 componentA.ts

ngOnInit(): void {
   this.songurl=this._allsongs.getData()[0];
   this.songname=this._allsongs.getData()[1];
  }

现在我面临的问题是 ngOnInit 仅在组件初始化时才有效,因此当有人单击组件 B 中的歌曲时,不会使用 getdata 发送歌曲详细信息。 请帮我解决这个问题。

【问题讨论】:

    标签: angular


    【解决方案1】:

    您需要在您的服务中使用主题并在您的组件 A 中订阅,请参阅 this SO 中的主题示例

    您的服务

      private mySubjectSource = new Subject<any>();
      myObservable=this.mySubjectSource.asObservable();
    
      constructor(){}
    
      sendValue(value:any)
      {
        this.mySubjectSource.next(value);
      }
    

    你的组件 A,在 ngOnInit 中

      constructor(private myService: MyService) {}
      ngOnInit()
      {
        this.myService.myObservable.subscribe(res=>{
          ..make something with the response...
        })
      }
    

    你的组件 B

       constructor(private myService: MyService) {}
       sendValue(value:any)
       {
         this.myService.sendValue(value);
       }
    

    fool example

    【讨论】:

    • 好的但是我如何发送我想要发送的数据而不是(值:any)我想发送多个值,例如 url name img 作为字符串
    • "value" 可以是一个对象:(click)="sendValue(song)"&gt;
    • 你能举个例子吗
    • 这是一个愚蠢的例子,但我希望可以帮助你:stackblitz.com/edit/…
    • 您可以创建“onfly”对象,但您只能发送对象或变量,但您可以解构响应。我更新了 stackblitz 来展示一个例子
    猜你喜欢
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 2019-12-10
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 2021-05-02
    • 2018-04-24
    相关资源
    最近更新 更多