3

我是 Polymer 的新手,目前正在学习Polymer 3.0。我正在尝试制作一个工作如下的应用程序:

  1. 从公共 url 获取播放列表数据(使用 iron-ajax 元素)
  2. 在handleResponse() 函数中处理数据,并将值分配给' playlistNames '变量。
  3. 使用路由显示播放列表和歌曲

问题:(我被困在哪里)

在刷新页面时http://127.0.0.1:8081/playlist1,路由器正在加载 404 页面而不是播放列表页面,因为playlistName是空的。但是,如果我单击任何播放列表(刷新页面后),路由器正在工作。

我无法playlistNames在不同的函数“_routePageChanged”中访问更新后的数组。代码片段如下。

handleResponse() func我得到正确的输出(带有播放列表列表的数组)。但在_routePageChanged() func'输出中是 [ ],一个空数组。

应用程序控制台输出屏幕截图


问题:

我的理解:app-route元素在iron-ajax元素之前处理。

如何访问playlistNamesin的新值_routePageChanged


文件:my-element.js

class MyApp extends PolymerElement {
    static get template() {
      return html `  
        <!-- make api calls to fetch the playlists -->
        <iron-ajax
                auto
                url=""
                handle-as = "json"
                on-response="handleResponse"
                last-response="{{ajaxResponse}}">
        </iron-ajax>

        <app-location route="{{route}}" url-space-regex="^[[rootPath]]">
        </app-location>

        <app-route route="{{route}}" pattern="[[rootPath]]:page" data="{{routeData}}" tail="{{subroute}}">
        </app-route>
  
        ...
            <iron-pages selected="[[page]]" attr-for-selected="name" role="main">
              <my-view404 name="view404"></my-view404>
              <data-send name="playlist" prop1="[[selectedPlaylist]]"></data-send>
            </iron-pages>
      `;
    }

    static get properties() {
      return {
        page: {
          type: String,
          reflectToAttribute: true,
          observer: '_pageChanged'
        },
        playlists: {
          type: Array,
          reflectToAttribute: true,
          value: 'waiting...',
          reflectToAttribute: true
        },
        playlistNames: {
          type: Array,
          value: function() {
            return [];
          }
        },
        selectedPlaylist: {
          type: String,
          value: 'selectedPlaylist is empty'
        },
        routeData: Object,
        subroute: Object
      };
    }

    static get observers() {
      return [
        '_routePageChanged(routeData.page, this.playlistNames.splices)'
      ];
    }
  
    // this function is called on api call
    handleResponse(event, request) { 
      //  get all the playlists from the api call response
      this.playlists = request.response.playlists;

      // get all the playlist names
      for(let playlist of this.playlists) {
        if(this.playlistNames.length < this.playlists.length) {
          // this.playlistNames.push(playlist.name);
          this.push('playlistNames', playlist.name);
        }  
      }
      console.log('handleResponse playlists', this.playlistNames); // ['playlist1', 'playlist2' ...]
  
      // on refreshing url, if any route is present, then find its id to fetch songs list from api
      if(this.routeData.page){
        for(let playlist of this.playlists){
          if(playlist.name === this.routeData.page){
            this.selectedPlaylist = playlist.id;
          }
        }
      }
    }

    // this func is called on route change or page refresh
    _routePageChanged(page, data) {
      console.log('routeData.page=', page);
      console.log('data=', data); // undefined
      console.log('_routePageChanged playlists.length=', this.playlistNames.length); // 0
      console.log('_routePageChanged playlists=', this.playlistNames); // empty  

      if (!page) {
        this.page = 'view404';
      } else if (["playlist1", "playlist2"].indexOf(page)  !== -1) {
      //playlistNames is empty[],
      // } else if (this.playlistNames.indexOf(page) !== -1) { 
        this.page = 'playlist';
      } else {
        this.page = 'view404';
      }
    }
  
    _pageChanged(page) {
      switch (page) {
        case 'view404':
          import('./my-view404.js');
          break;
        case 'playlist':
          import('./playlist-songs.js');
          break;
      }
    }
  }

4

1 回答 1

3

编辑:改进的答案

正如您在评论中所说,当路由更改为视图时,_routePageChanged()将始终在之前运行handleResponse()(因为handleResponse()是异步的)所以无论做什么handleResponse(),只会在之后执行_routePageChanged()

如果您要遵循我的解决方案,则需要首先对数组属性进行playlistNames可观察的更改,因此:

代替:

this.playlistNames.push(playlist.name);

利用:

this.push('playlistNames', playlist.name);

如此处所述

解决方案 - 如果您真的需要检查_routePageChanged()

您可以更改_routePageChanged为观察两个属性,而不仅仅是一个属性page。因此_routePageChanged(page),您可以将观察者声明为_routePagePlaylistNamesChanged(page, playlistNames)并在其中包含逻辑,而不是 。这样,观察者将在两个属性中的任何一个更改值时触发,并且您可以在其中包含逻辑,例如:

_routePagePlaylistNamesChanged(page, playlistNames) {
  if(page == "myelement" && playlistNames.length > 0){
    //This is correct page and the playlistNames are defined
    console.log('_routePagePlaylistNamesChanged playlists', this.playlistNames);
  }
}
于 2018-08-21T16:09:13.953 回答