zoukankan      html  css  js  c++  java
  • [Angular] Data Resolver

    // course-detail.resolver.ts 
    
    import {Resolve, ActivatedRouteSnapshot, RouterStateSnapshot} from "@angular/router";
    import {Course} from "../shared/model/course";
    import {Lesson} from "../shared/model/lesson";
    import {Observable} from "rxjs";
    import {Injectable} from "@angular/core";
    import {CoursesService} from "../services/courses.service";
    
    
    @Injectable()
    export class CourseDetailResolver implements Resolve<[Course,Lesson[]]> {
    
        constructor(private coursesService: CoursesService) {}
    
        resolve(
            route: ActivatedRouteSnapshot,
            state: RouterStateSnapshot): Observable<[Course, (Lesson[])]> {
    
            return this.coursesService.findCourseByUrl(route.params['id'])
                .switchMap(
                    course => this.coursesService.findLessonsForCourse(course.id),
    (course, lessons) => [course, lessons]
    ); } }

    The highlighted code is a combinator, which combine inner and outter observables and return a new Tuple type.

    Router:

        {
            path: 'course/:id',
            component: CourseDetailComponent,
            resolve: {
                detail: CourseDetailResolver
            }
        },

    Component:

      
    import {Component, OnInit} from '@angular/core';
    import {ActivatedRoute} from '@angular/router';
    import {Course} from "../shared/model/course";
    import {Lesson} from "../shared/model/lesson";
    import {Observable} from "rxjs";
    
    
    @Component({
        selector: 'course-detail',
        templateUrl: './course-detail.component.html',
        styleUrls: ['./course-detail.component.css']
    })
    export class CourseDetailComponent implements OnInit {
    
        course$: Observable<Course>;
        lessons$: Observable<Lesson[]>;
    
        constructor(private route: ActivatedRoute) {
    
        }
    
        ngOnInit() {
    
            this.course$ = this.route.data.map(data => data['detail'][0]);
    
            this.lessons$ = this.route.data.map(data => data['detail'][1]);
    
        }
    
    
    }
  • 相关阅读:
    0593. Valid Square (M)
    0832. Flipping an Image (E)
    1026. Maximum Difference Between Node and Ancestor (M)
    0563. Binary Tree Tilt (E)
    0445. Add Two Numbers II (M)
    1283. Find the Smallest Divisor Given a Threshold (M)
    C Primer Plus note9
    C Primer Plus note8
    C Primer Plus note7
    C Primer Plus note6
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13843865.html
Copyright © 2011-2022 走看看