[Thực hành] Ứng dụng nghe nhạc- Codegym.vn

Apr 22, 2020 | Bài thực hành, Blog | 0 comments

Mục tiêu

Ứng dụng nghe nhạc- nắm bắt được về các thao tác với service và router trong Angular.

Mô tả- ứng dụng nghe nhạc

Tạo ứng dụng nghe nhạc

Hướng dẫn

Bước 1: Khởi tạo project với Angular CLI (nếu đã có project thì có thể bỏ qua)

Các bạn chạy lệnh npm i typescript@2.9.2 -D để cài đặt thư viện typescript nếu phiên bản hiện tại < 2.9.2

Bước 2: Khởi tạo hai component mới trong project và đặt tên là youtube-playlist, youtube-player

Khởi tạo một service mới tên là youtube.

Tạo file app-routing.module.ts (bỏ qua nếu dùng project mẫu)

Bước 3: update file routing vừa tạo:

const routes: Routes = [
    {
        path: 'youtube',
        component: YoutubePlaylistComponent,
        children: [{
            path: ':id',
            component: YoutubePlayerComponent
        }]
    }
];

@NgModule({
    imports: [RouterModule.forRoot(routes, {
        preloadingStrategy: PreloadAllModules
    })],
    exports: [RouterModule]
})
export class AppRoutingModule {}

Bước 4: update file app.module.ts

@NgModule({
    declarations: [
        AppComponent,
        YoutubePlaylistComponent,
        YoutubePlayerComponent
    ],
    imports: [
        BrowserModule,
        AppRoutingModule
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

Bước 5: update code của service vừa tạo

import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class YoutubeService {
    playlist = [
        {id: 'CX11yw6YL1w', song: 'Céline Dion - Ashes (from the Deadpool 2 Motion Picture Soundtrack)'},
        {id: 'HBYirj2c_jw', song: 'Deadpool 2 - Take on Me'},
        {id: 'N6O2ncUKvlg', song: 'Nelly - Just A Dream'},
        {id: 'uelHwf8o7_U', song: 'Eminem - Love The Way You Lie ft. Rihanna'},
        {id: 'WpYeekQkAdc', song: 'The Black Eyed Peas - Where Is The Love?'}
    ];
    constructor() { }
    find(id: string) {
        return this.playlist.find(item => item.id === id);
    }
}

Bước 6: update code cho youtube playlist

Template:

<h2>Youtube playlist</h2>
<ul>
    <li *ngFor="let item of youtubeService.playlist">
        <a [routerLink]="['/youtube', item.id]">{{item.song}}</a>
    </li>
</ul>

<router-outlet></router-outlet>

Component:

import { Component, OnInit } from '@angular/core';
import { YoutubeService } from '../youtube.service';

@Component({
    selector: 'app-youtube-playlist',
    templateUrl: './youtube-playlist.component.html',
    styleUrls: ['./youtube-playlist.component.scss']
})
export class YoutubePlaylistComponent implements OnInit {

    constructor(public youtubeService: YoutubeService) { }

    ngOnInit() {
    }
}

Bước 7: update code cho youtube player

Template:

<div *ngIf="song; else tmpl">
    <h2>Song name: {{song.song}}</h2>
    <iframe width="560" height="315" [src]="getSrc()" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>

<ng-template #tmpl>
    <h2>Nothing to play</h2>
</ng-template>

Component:

import { Component, OnInit, OnDestroy } from '@angular/core';
import { YoutubeService } from '../youtube.service';
import { ActivatedRoute, ParamMap } from '@angular/router';
import { Subscription } from 'rxjs';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
    selector: 'app-youtube-player',
    templateUrl: './youtube-player.component.html',
    styleUrls: ['./youtube-player.component.scss']
})
export class YoutubePlayerComponent implements OnInit, OnDestroy {
    song: any;
    sub: Subscription;
    constructor(
        private youtubeService: YoutubeService,
    private activatedRouter: ActivatedRoute,
    private domSanitizer: DomSanitizer
) { }

ngOnInit() {
    this.sub = this.activatedRouter.paramMap.subscribe((paramMap: ParamMap) => {
        const id = paramMap.get('id');
        this.song = this.youtubeService.find(id);
    });
}

getSrc() {
    const url = 'https://www.youtube.com/embed/' + this.song.id;
    return this.domSanitizer.bypassSecurityTrustResourceUrl(url);
}

ngOnDestroy() {
    this.sub.unsubscribe();
}

}

Bước 8: update code cho app.component.html

<nav>
    <a routerLink="youtube" class="link">Youtube</a>
</nav>
<router-outlet></router-outlet>

Bước 9: kiểm tra kết quả

Mã nguồn tham khảo: https://github.com/codegym-vn/angular-training/tree/master/angular-service-router/src/app

Trên đây CodeGym đã cùng với bạn luyện tập về các thao tác với service và router trong Angular. Hãy chụp ảnh màn hình và nộp bài thực hành của bạn trên CodeGymX để cùng nhau luyện tập nhé!

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

BÀI VIẾT LIÊN QUAN

BẠN MUỐN HỌC LẬP TRÌNH?

GỌI NGAY 

098 953 44 58

Nhận tư vấn, định hướng 1-1

Điền và gửi thông tin cá nhân để được tư vấn miễn phí về các chương trình học.

13 + 9 =