簡體   English   中英

Angular 6使用HttpClient,RxJS和GroupBy顯示數據

[英]Angular 6 display data with HttpClient, RxJS and GroupBy

我在后端使用Ruby on Rails API應用程序,在前端使用Angular 6。 這是我從后端得到的json響應:

loclhost3000 / courses.json

 [ { id:1, title:"Introduction", author:"Dana Inbar", segments:[ ] }, { id:2, title:"Master the ELN", author:"Dana Inbar", segments:[ ] }, { id:3, title:"Master the Inventory", author:"Dana Inbar", segments:[ { id:1, unit_id:1, unit_title:"Introduction", name:"Lesson 1: Introduction to the inventory module- looking at one collection", data:"www.video01.com/vid.avi" }, { id:2, unit_id:2, unit_title:"Inventory Customisation", name:"Lesson 2: Setting up custom collections", data:"www.video02.com/vid.avi" }, { id:3, unit_id:2, unit_title:"Inventory Customisation", name:"Lesson 3: Adding a custom field", data:"www.video03.com/vid.avi" }, { id:4, unit_id:2, unit_title:"Inventory Customisation", name:"Lesson 4: Creating derived collections", data:"www.video04.com/vid.avi" }, { id:5, unit_id:2, unit_title:"Inventory Customisation", name:"Lesson 5: Using repositories", data:"www.video05.com/vid.avi" }, { id:6, unit_id:2, unit_title:"Inventory Customisation", name:"Quiz", data:"'[ { " question 1":"___", "answers":{ "1":"____", "2":"____", "3":"____" }, "correct_answer":"2" }, { "question 2":"___", "answers":{ "1":"____", "2":"____" }, "correct_answer":"1" } } ] ' " } ] } ] 

我的課程模型有很多細分,而細分是視頻或測驗。 我有課程清單,課程細節和課程玩法組件。 我對課程詳細信息有疑問,我希望課程詳細信息頁面看起來像這樣: 課程詳細信息圖像

我以為我可以在course.service中執行將unitBid與unit_id和unit_title結合使用並執行兩個ngFor(或ngFor group)的函數,但是由於我對angular不熟悉,所以我不知道如何最好地實現這一點。

我正在從程序中添加一些文件,這可以幫助您:

./courses/course.module

 import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { RouterModule, Routes } from '@angular/router'; import { MatSidenavModule } from '@angular/material/sidenav'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { CourseListComponent } from './course-list/course-list.component'; import { CourseDetailComponent } from './course-detail/course-detail.component'; import { CourseService } from './course.service'; import { CoursePlayComponent } from './course-play/course-play.component'; const coursesRoutes: Routes = [ { path: 'courses', component: CourseListComponent }, { path: 'courses/:id', component: CourseDetailComponent }, { path: 'courses/:id/:segment_id', component: CoursePlayComponent } ] @NgModule({ imports: [ CommonModule, MatSidenavModule, BrowserAnimationsModule, RouterModule.forChild( coursesRoutes ) ], declarations: [ CourseListComponent, CourseDetailComponent, CoursePlayComponent ], providers: [ CourseService ] }) export class CourseModule { } 

./courses/course

 export interface ICourse { course_id: number; title: string; autor: string; segments: ISegment[]; } export interface ISegment { segment_id: number; unit_id: number; unit_title: string; name: string; type: string; data: string; } 

./courses/course.service

 import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { map, catchError, retry, groupBy, Filter } from 'rxjs/operators'; import { Course } from './course'; // Inject Data from Rails app to Angular app @Injectable() export class CourseService{ constructor(private http: HttpClient) { } private url = 'http://localhost:3000/courses'; private courseUrl = 'http://localhost:3000/courses.json'; // Handle Any Kind of Errors private handleError(error: HttpErrorResponse) { // A client-side or network error occured. Handle it accordingly. if (error.error instanceof ErrorEvent) { console.error('An error occured:', error.error.message); } // The backend returned an unsuccessful response code. // The response body may contain clues as to what went wrong. else { console.error( 'Backend returned code ${error.status}, ' + 'body was ${error.error}'); } // return an Observable with a user-facing error error message return throwError( 'Something bad happend; please try again later.'); } // Get All Courses from Rails API App getCourses(): Observable<ICourse[]> { const coursesUrl = `${this.url}` + '.json'; return this.http.get<ICourse[]>(coursesUrl) .pipe( catchError(this.handleError) ); } // Get Single Course by id. will 404 if id not found getCourse(id: number): Observable<ICourse> { const detailUrl = `${this.url}/${id}` + '.json'; return this.http.get<ICourse[]>(detailUrl) .pipe( catchError(this.handleError) ); } } 

./courses/course-detail/course-detail.component

 import { Component, OnInit } from '@angular/core'; import { ActivatedRoute, Router } from '@angular/router'; import { Course } from '../course'; import { CourseService } from '../course.service'; @Component({ selector: 'lg-course-detail', templateUrl: './course-detail.component.html', styleUrls: ['./course-detail.component.sass'] }) export class CourseDetailComponent implements OnInit { course: ICourse; errorMessage: string; constructor(private courseService: CourseService, private route: ActivatedRoute, private router: Router) { } ngOnInit() { const id = +this.route.snapshot.paramMap.get('id'); this.getCourse(id); } // Get course detail by id getCourse(id: number) { this.courseService.getCourse(id).subscribe( course => this.course = course, error => this.errorMessage = <any>error); } onBack(): void { this.router.navigate(['/courses']); } } 

./courses/course-detail/course-detail.html

 <div id="main" *ngIf="course"> <div class="row" id="image"> <div class="col-lg-8"> <br> <img src="./assets/images/lg-white.png" class="d-inline-block align-top" alt=""> </div> </div> <div class="row" id="header"> <div class="container text-center"> <br> <h1>{{course.title}}</h1> <br> </div> </div> <div class="row justify-content-lg-center" id="progress"> <div class="container text-center"> <div class="progress"> <div class="progress-bar bg-white"></div> </div> <td>Your Progress</td> <br><br><br> </div> </div> <div class="row" id="body"> <div class="container"> <br> <ul class="nav nav-tabs" role="tablist"> <li class="nav-item"> <a class="nav-link active" href="#Curiculum" role="tab" data-toggle="tab">Curiculum</a> </li> <li class="nav-item"> <a class="nav-link" href="#About" role="tab" data-toggle="tab">About this course</a> </li> </ul> <br> <!-- Tab panes --> <div class="tab-content"> <div role="tabpanel" class="tab-pane fade in active" id="Curiculum"> <h1>Course Overview</h1> <br> <ul *ngFor="let segment of course.segmentsByUnitId"> <ul> <li id="title">Unit {{segment.unit_id}}: {{segment.unit_title}}</li> <li>{{segment.name}}</li> </ul> </ul> </div> <div role="tabpanel" class="tab-pane fade" id="About"> <h1>Course Topics:</h1> </div> </div> <br> </div> </div> </div> 

./courses/course-detail/course-detail.sass

 $color: #FFFFFF $bg-col: #5c0099 $prog-size: 10px #image background-color: $bg-col color: $color #header background-color: $bg-col color: $color #body background-color: $color height: 100vh max-width: initial display: flex #title font-weight: bold #progress background-color: $bg-col color: $color font-size: $prog-size .progress height: 10px left: 30% .progress-bar width: 10% height: 20px background-color: transparent 

您可以使用以下groupby管道來實現。 GroupBy管道返回鍵/值對的對象。 https://github.com/danrevah/ngx-pipes#groupby

ngx-pipes的安裝過程: https : //github.com/danrevah/ngx-pipes#installation

下面是我為數據實現它的方式:我的數據:

tsks = [{
      CompletedFlag: true,
      ProgressFlag: false,
      DueDate:"2014-10-02T13:12:37.027",
      Signup: "2014-10-04T11:51:10.137",
      ObMilestone: 1,
      ObTask: 119,
      AssignedToId: 0,
      Company: "ABC Corp",
      Description: "Lorem Ipsum",
      Favourite: null,
      FirstName: "Libin",
      LastName: "J",
      MilestoneName: "Blue",
      OnboarderStatus: "Live",
      Partner : null
    },
    {
     CompletedFlag: true,
      ProgressFlag: false,
      DueDate:"2014-10-02T13:12:37.027",
      Signup: "2014-10-04T11:51:10.137",
      ObMilestone: 1,
      ObTask: 119,
      AssignedToId: 0,
      Company: "ABC Corp",
      Description: "Lorem Ipsum",
      Favourite: null,
      FirstName: "Libin",
      LastName: "J",
      MilestoneName: "Blue",
      OnboarderStatus: "Live",
      Partner : null
    }];

將我的代碼分組為“ MilestoneName”

<div class="row" *ngFor="let task of tsks | groupBy: 'MilestoneName' | pairs">
  <div>Group milestone name: {{task[0]}}</div>

  <div class="row" *ngFor="let t of task[1]">
    <div>Task: {{t.FirstName}}</div>
  </div>
</div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM