Angular 4 + firebase,输出对象中的嵌套对象

时间:2017-05-13 09:29:54

标签: angular firebase

我的火力基地:

public class BackgroundService extends Service implements OnCompletionListener
    {
        MediaPlayer mediaPlayer;
        private String STREAM_URL;
        final String textSource = "http://audiophileradio.stream/Ip.txt";

        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }

        @Override
        public void onCreate()
        {

        }

        @Override
        public int onStartCommand(Intent intent, int flags, int startId)
        {
            new MyTask().execute();

            return START_STICKY;
        }

        public void onDestroy() {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();
            }
            mediaPlayer.release();
        }

        public void onCompletion(MediaPlayer _mediaPlayer) {
            stopSelf();
        }


        @Override
        public boolean onUnbind(Intent intent)
        {
            return super.onUnbind(intent);
        }

        private class MyTask extends AsyncTask<Void, Void, String>
        {
            String textResult;

            @Override
            protected String doInBackground(Void... params) {

                URL textUrl;

                try {
                    textUrl = new URL(textSource);

                    BufferedReader bufferReader
                            = new BufferedReader(new InputStreamReader(textUrl.openStream()));

                    String StringBuffer;
                    String stringText = "";
                    while ((StringBuffer = bufferReader.readLine()) != null) {
                        stringText += StringBuffer;
                    }
                    bufferReader.close();

                    textResult = stringText;
                    return textResult;
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                    textResult = e.toString();
                } catch (IOException e) {
                    e.printStackTrace();
                    textResult = e.toString();
                }

                return null;

            }

            @Override
            protected void onPostExecute(String result) {

                Log.d("DebugTag", "Value: " + textResult);

                super.onPostExecute(result);

                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(BackgroundService.this);
                String radio = sharedPreferences.getString("station", "8000");

                if (radio != null)
                {
                    STREAM_URL += ":" + radio;
                }

                mediaPlayer = new MediaPlayer();

                if (!mediaPlayer.isPlaying())
                {
                    try
                    {
                        mediaPlayer.reset();
                        mediaPlayer.setDataSource(STREAM_URL);
                        mediaPlayer.prepareAsync();

                        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
                        {
                            @Override
                            public void onPrepared(MediaPlayer mp)
                            {
                                mediaPlayer.start();
                            }
                        });
                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    }

                }

                mediaPlayer.setOnCompletionListener(BackgroundService.this);
            }
        }

    }


public class Main extends Fragment
{
    private ImageButton buttonPlay;
    private MediaPlayer mPlayer;
    Intent playbackServiceIntent;

    private SeekBar volumeSeekbar = null;
    private AudioManager audioManager = null;

    View view;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        view = inflater.inflate(R.layout.fragment_main,container,false);

        buttonPlay = (ImageButton) view.findViewById(R.id.buttonPlay);

        mPlayer = new MediaPlayer();

        initControls();

        buttonPlay.setTag(1);
        buttonPlay.setImageResource(R.drawable.play);
        buttonPlay.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                if (Integer.parseInt(buttonPlay.getTag().toString()) == 1)
                {
                    buttonPlay.setImageResource(R.drawable.stop);
                    view.setTag(0);

                    getActivity().startService(playbackServiceIntent);

                    Log.e("Play", "onStop");
                    Toast.makeText(getActivity(), "Play", Toast.LENGTH_SHORT).show();
                } else
                {
                    buttonPlay.setImageResource(R.drawable.play);
                    view.setTag(1);
                    mPlayer.stop();
                    getActivity().stopService(playbackServiceIntent);
                    Log.e("Stop", "onPlay");
                    Toast.makeText(getActivity(), "Stop", Toast.LENGTH_SHORT).show();
                }

            }
        });
        playbackServiceIntent = new Intent(getActivity(), BackgroundService.class);

        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState)
    {
        super.onViewCreated(view, savedInstanceState);

        getActivity().setTitle("Audiophileradio");
    }

    private void startService()
    {
        getActivity().startService(new Intent(getActivity(),BackgroundService.class));
    }
    private void stopService()
    {
        getActivity().stopService(new Intent(getActivity(),BackgroundService.class));
    }

    private void initControls()
    {
        try
        {
            volumeSeekbar = (SeekBar) view.findViewById(R.id.seekBar);
            audioManager = (AudioManager) getActivity().getSystemService(Context.AUDIO_SERVICE);
            volumeSeekbar.setMax(audioManager
                    .getStreamMaxVolume(AudioManager.STREAM_MUSIC));
            volumeSeekbar.setProgress(audioManager
                    .getStreamVolume(AudioManager.STREAM_MUSIC));
            //volumeSeekbar.setMax(100);
            volumeSeekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener()
            {
                @Override
                public void onStopTrackingTouch(SeekBar arg0)
                {
                }

                @Override
                public void onStartTrackingTouch(SeekBar arg0)
                {
                }

                @Override
                public void onProgressChanged(SeekBar arg0, int progress, boolean arg2)
                {
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
                            progress, 0);

                    //volume.setText("Volume : " + progress + "%");
                }
            });
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

我如何输出图像? 我在component.ts中的代码

 {
      "hotel" : {
        "-Kjgyamcup6ULm0Awa-1" : {
          "complete" : "true",
          "images" : {
            "-Kjgyb6A2gRiDhwaWx-V" : {
              "name" : "2.jpg",
              "url" : "https://firebasestorage.googleapis.com/v0/b/teplo-31a17.appspot.com/o/hotel%2F-Kjgyamcup6ULm0Awa-1%2Fimages%2F2.jpg?alt=media&token=0faffb92-9bc5-44ce-9189-ee405137c3bf"
            },
            "-KjgybAKrkf3EzYxvgGD" : {
              "name" : "4.jpg",
              "url" : "https://firebasestorage.googleapis.com/v0/b/teplo-31a17.appspot.com/o/hotel%2F-Kjgyamcup6ULm0Awa-1%2Fimages%2F4.jpg?alt=media&token=bd7ebc47-b14d-46e5-a58d-01d647fcf95d"
            }
          },
          "number" : "102",
          "price" : "2500"
        }, etc

和html

 export class UserComponent implements OnInit {

 hotelNumbers: FirebaseListObservable<any[]>;

  constructor(private af: AngularFire) { 

    this.hotelNumbers = af.database.list('/hotel');

  }

  ngOnInit() {
  }


}

如何输出图像(* ngFor =“hotel.number.images | async”的图像) - 没有工作

2 个答案:

答案 0 :(得分:1)

可以解决问题如下:

通过建议rmekarni编辑我的数据库:

database

编辑component.ts文件

 constructor(private af: AngularFire) { 

    this.hotelNumbers = af.database.list('/hotel').map((myhotels) =>{
      return myhotels.map(myhotel =>{
        myhotel.img = af.database.list('/images/' + myhotel.$key);
        return myhotel;   
      });
    });

  }

编辑html文件

<div *ngFor="let myhotel of hotels | async">
  <p>{{myhotel.number}}</p>
  <div *ngFor="let img of myhotel.img | async">
      <img src="{{img.url}}">
  </div>
</div>

答案 1 :(得分:0)

this.hotels = af.database.list('/hotel');

Firebase很棒,因为它将一个observable与一个数组合并。因此,您可以将af.database.list('/hotel')返回的observable视为数组,并在其上执行带有异步管道的ngFor:

<div *ngFor="let hotel of hotels | async">
  <p>{{hotel.images}}</p>
  etc
</div>

这是因为hotel是一个项目(JSON对象中的一个键),它有images属性(价格,完整等)

如果您想迭代所有酒店的图片,那么您的数据结构是错误的。您应该对其进行非规范化并使数据结构变平。这里有一篇关于它的优秀文章,你必须阅读它! Firebase doc - structure your database

如果您真的想保留该数据结构,则无法使用异步管道直接迭代图像。您有订阅您的酒店并通过回调获取图像嵌套对象。我认为你必须通过用Object.keys(json).forEach(key => json[key]...);迭代你的嵌套json来创建一个数组,然后在ngFor指令中使用该数组......