首页 > 解决方案 > 如何以角度将数组元素推入库元素类型

问题描述

我正在使用一个处理音乐曲目的库,并且曲目数组有一个名为“track”的类型,它有一个标题和一个指向相关曲目的链接。像这样:

Playlist: Track[] = [
  {
    title: 'Audio One Title',
    link: 'Link to Audio One URL'
  },
  {
    title: 'Audio Two Title',
    link: 'Link to Audio Two URL'
  },
  {
    title: 'Audio Three Title',
    link: 'Link to Audio Three URL'
  },
];

我正在尝试以递归方式加载它,所以我已经对其进行了初始化:

  msaapPlaylist: Track[] = [];

我正在尝试从另一个数组中推入它,例如:

  this.msaapPlaylist.push([song.title, song.link]);

它说我不能将 type: any 推送到 Track 中,因为它缺少 Track: 'title' 和 'link' 类型的属性,这是有道理的!但我不知道该怎么走。任何指示都将是可观的。

编辑 以回应评论,这就是我正在做的事情。有一个 mapquest api 函数可以根据行程长度构建播放列表。

import { Component, OnInit } from '@angular/core';

import { Observable, Subject, combineLatest} from 'rxjs';

import { debounceTime, distinctUntilChanged, switchMap} from 'rxjs/operators';
import {MapQuestService} from '../services/mapQuest.service';
import { HttpClient} from '@angular/common/http';
import * as _ from 'lodash';
import { Track } from 'ngx-audio-player';
import { faCoffee } from '@fortawesome/free-solid-svg-icons';



class ToAndFromVals {
  constructor(public readonly from: string, public readonly to: string) {}
}


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

export class AppComponent implements OnInit {
  faCoffee = faCoffee;
  title = 'hw5-part1';
  distResult: any;
  timeResult: any;
  maneuvs: any;
  to: any;
  from: any;
  musicData: any[];
  travelTime: any;
  playList: any[] = [];
  playListLength: number;
  msaapDisplayTitle = true;
  msaapDisplayPlayList = true;
  msaapPageSizeOptions = [2, 4, 6];
  msaapDisplayVolumeControls = true;
  // Material Style Advance Audio Player Playlist
  msaapPlaylist: Track[] = [ ];




  private searchTerms: Subject<ToAndFromVals>;


  constructor(private mapQuestService: MapQuestService, private http: HttpClient) {  }

  parseMusic(data: any) {
    const timeRegex = /^(\d+):(\d+)$/;
    for (let song of data) {
      let matchsong = song.length.match(timeRegex);
      let secondsTotal = (parseInt(matchsong[1], 10) * 60) + parseInt(matchsong[2], 10);
      song.totalSeconds = secondsTotal;
    }
    this.musicData = data;
  }


  search(from: string, to: string): void {
    if ( from && to ) {
    let searchy = new ToAndFromVals(from, to);
    this.searchTerms.next(searchy); }}

  ngOnInit() {

    this.searchTerms = new Subject<ToAndFromVals>();
    this.searchTerms.pipe(
        debounceTime(1000),
        distinctUntilChanged(),
        switchMap((x) => {
          return this.mapQuestService.getMap(x.from, x.to);

        }))
      .subscribe((result: any) => {
        console.log(result);
        this.distResult = result.route.distance;
        this.timeResult = result.route.formattedTime;
        this.maneuvs = result.route.legs[0].maneuvers;
        this.travelTime = result.route.time;
        this.createPlaylist();
      });


    // http request to fetch song data and store it

    let url: string = "assets/musicData.json";
    this.http.get(url).subscribe(
      (data: any) => {
      this.parseMusic(data);
      });

    }
    // shuffles list so user doesnt hear same songs over and over
    createPlaylist() {
      this.playList.length = 0;
      this.playListLength = 0;
      let shuffledlist = _.shuffle(this.musicData);
      for (let song of shuffledlist) {
        let left = this.travelTime - this.playListLength;
        if (song.totalSeconds <= left) {
          this.playList.push(song);
          // this.msaapPlaylist.push({title: 'stoofleberg', link: 'assets/music/Ghost Story.mp3', index: 1});
          this.msaapPlaylist.push({title: song.title, link: song.link});
          this.playListLength += song.totalSeconds;
        }
      }
      console.log(this.playList, 'and', this.travelTime, 'and', this.playListLength);
      console.log(this.msaapPlaylist);
    }



    formatTime(seconds){
      if (seconds ===undefined || seconds === null){
        return '';
      }

      let minute = Math.floor(seconds / 60);
      let secondsThing = seconds % 60;
      let hour = Math.floor(minute / 60);
      minute = minute % 60;
      // tslint:disable-next-line: max-line-length
      let wholeThing = hour.toString().padStart(2, '0') + ':' + minute.toString().padStart(2, '0') + ':' + secondsThing.toString().padStart(2, '0');
      return wholeThing;
    }

ngAfterViewInit() {
    this.search('boston', 'poughkeepsie');
  }
}

HTML

 <div class="container">
  <h3>HW5-p1</h3>

  <form >
         <input
         #from
         id="from"
         (keyup)="search(from.value, to.value)" placeholder="From" value="boston"/>

          <input
          #to
          id="to"
          (keyup)="search(from.value, to.value)" placeholder="To" value="poughkeepsie"/>
  </form>

  <hr/>
  <h2>Songs and Lengths</h2>
  <h3>Travel Length {{formatTime(travelTime)}}</h3>
  <h3>Playlist Length {{formatTime(playListLength)}}</h3>
  <ul id="playMusic" *ngFor='let song of playList'>
    <li><a href='assets/music/{{song.title}}.mp3' target='_blank'>{{song.title}}</a> {{song.length}}</li>
  </ul>
</div>



  <hr/>
  <table class="table table-striped" id='maps'>

      <tr><th colspan="4"> Distance: {{distResult}} miles  -  Time: {{timeResult}} </th></tr>
      <tbody *ngFor="let m of maneuvs">
        <tr>
          <td><a href='{{m.iconUrl}}' target=_x>
            <img src="{{m.iconUrl}}"/>
          </a></td>
          <td>{{m.index + 1}}. </td>
          <td>
              <a  href='{{m.mapUrl}}' target=_x>
                  {{m.narrative}} </a>
          </td>
          <td>{{m.distance}}</td>

        </tr>
      </tbody>

    </table>

<div class="container" id="BobDiv">
  <mat-advanced-audio-player [playlist]="msaapPlaylist" [displayTitle]="msaapDisplayTitle"
  [displayPlaylist]="msaapDisplayPlayList" [pageSizeOptions]="msaapPageSizeOptions"
      [displayVolumeControls]="msaapDisplayVolumeControls" [expanded]="true"></mat-advanced-audio-player>
</div>


<router-outlet></router-outlet>

标签: angulartypeslibraries

解决方案


您正在尝试推送一个字符串数组,而不是一个对象,假设类型Track

interface Track {
   title: string;
   link: string
}

尝试:

this.msaapPlaylist.push(
  { title: song.title, link: song.link }
);

推荐阅读