1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Angular update Tab A from Tab B using a service

Discussão em 'Angular' iniciado por David Alejandro García, Setembro 30, 2024.

  1. I'm a Jr talking about Angular, I have a question:

    Context: A Teacher can own multiple Students.

    1. Requirement # 1.- They want to be able to open a new tab from the Teacher Admin page for each Student. This is working
    2. Requirement # 2.- When you click on Save on one of the Students Admin, the Teachter Admin page should refreshed.

    Is requirement 2 technically possible?

    Student Api Service

    export class StudentApiService extends BaseService {
    protected endPoint = "student/student";

    private lastStudentUpdate$$: Subject<StudentUpdate> = new Subject<StudentUpdate>();
    public lastStudentUpdate$: Observable<StudentUpdate> = this.lastStudentUpdate$$.asObservable();

    getStudent(id: number) : Observable<any>
    {
    return this.get( {id: id});
    }

    getStudents(teacherId: number): Observable<any> {
    return this.get({ teacherId: teacherId });
    }

    createPendingStudent(model: StudentCreate) : Observable<any>
    {
    return this.post(model);
    }

    updateStudent(model: StudentUpdate) : Observable<any>
    {
    this.lastStudentUpdate$$.next(model);
    return this.put(model);
    }


    }

    teacher-wizard.component.ts

    @Component({


    selector: 'app-teacher-wizard',
    templateUrl: './teacher-wizard.component.html',
    styleUrls: ['./teacher-wizard.component.scss']
    })
    export class TeacherWizardComponent implements OnInit, OnDestroy {

    id: number;
    lastStudentUpdate$: Observable<StudentUpdate>;

    constructor(
    private route: ActivatedRoute,
    private studentApiService: StudentApiService,
    private router: Router
    ) { }

    checkParams(params: ParamMap) {
    const teacherId = 'teacherId';
    if (!params.has(teacherId)) {
    return;
    }
    this.id = +params.get(teacherId);
    }

    ngOnInit() {

    let sub = this.route.parent.url.pipe(
    withLatestFrom(this.route.parent.paramMap)
    ).subscribe(([url, paramMap]) => {
    this.checkParams(paramMap);
    this.getRoutes();
    });
    this.subs.push(sub);
    this.subs.push(routingEventSub);
    this.lastStudentUpdate$ = this.studentApiService.lastStudentUpdate$
    .pipe(startWith(undefined));

    this.lastStudentUpdate$.subscribe((x)=>{
    console.log(x);
    })
    }

    getRoutes() {
    const cr: Routes = this.route.snapshot.routeConfig.children.filter(x => x.path.length > 0);
    this.childRoutes = cr.map(x => (
    {
    exact: !x.children,
    display: x.data.display,
    path: x.path,
    iconClass: x.data?.iconClass,
    tooltip: x.data?.tooltip,
    component: x.component,
    displayOnlyOnRoute: x.data?.displayOnlyOnRoute === true,
    isExclusiveOperation: x.data?.isExclusiveOperation === true,
    }));
    }

    ngOnDestroy(): void {
    this.formService.destroyFormGroup(this.formGroup);
    this.subs.forEach(sub => sub.unsubscribe());
    }
    }


    student-wizard.component.ts

    @Component({
    selector: 'student-wizard',
    templateUrl: './student-wizard.component.html',
    styleUrls: ['./student-wizard.component.scss'],
    })
    export class StudentWizardComponent implements OnInit, OnDestroy {
    id: number;
    student: string;
    private subs: Subscription[] = [];
    formGroup: UntypedFormGroup;
    childRoutes: Array<any>;
    lastStudentUpdate$: Observable<StudentUpdate>;

    constructor(
    private _router: Router,
    private route: ActivatedRoute,
    private studentApiService: StudentApiService,
    private formService: StudentEditFormService
    ) { }

    checkParams(params: ParamMap) {
    const studentId = 'studentId';
    if (!params.has(studentId)) {
    return;
    }
    this.id = +params.get(studentId);
    }

    ngOnInit() {
    this.currentlySaving = false;
    const sub1 = this.route.params.pipe(
    withLatestFrom(this.route.parent.paramMap),
    switchMap(([url, paramMap]) => {
    this.checkParams(paramMap);
    this.getRoutes();
    return this.studentApiService.getStudent(this.id)
    }),
    switchMap(x => {
    this.student = x.student;
    return this.formService.createFormGroup(x)
    })
    ).subscribe(fg => {
    this.formGroup = fg;
    new FormDirtyCheckerService(fg);
    });

    this.subs = [sub1];

    this.lastStudentUpdate$ = this.studentApiService.lastStudentUpdate$
    .pipe(startWith(undefined));

    this.lastStudentUpdate$.subscribe((x)=>{
    console.log(x);
    })
    }
    ngOnDestroy(): void {
    this.subs.forEach(s => s.unsubscribe());
    this.formService.destroyFormGroup(this.formGroup);
    }

    getLastSegment() {
    return window.location.pathname.split('/').slice(-1)[0];
    }

    save($event) {
    this.doSave(false);
    }

    saveAndBack($event) {
    this.doSave(true);
    }

    doSave(returnToAdmin) {
    if (!this.formGroup.dirty) {
    //No changes detected;
    return;
    };
    this.currentlySaving = true;
    return this.studentApiService.updateStudent(model);
    }


    hasWarnings(formGroup : UntypedFormGroup) {
    if (!formGroup?.controls) return false;
    const found = Object.keys(formGroup.controls).find(key => {
    const ctrl : AbstractControlExtended = formGroup.get(key);
    return ctrl.warnings !== undefined && ctrl.warnings !== null;
    });
    return found !== undefined;
    }
    }
    }


    with this example code I have the next behavior:


    1. I Open Teacher Admin Page, I have listed the Students, I can Open New Tabs for each Students


    2. I added an observable to Student Api Service (lastStudentUpdate)


    3. When I click save in Student Admin Page I do see in Student Admin Page console:

      undefined

      lastUpdatedStudent info

      undefined


    4. I dont see lastUpdatedStudent info in Teacher Admin Page Console, only an undefined due subscription startwith undefined

    any idea?

    I'm using

    • Visual Studio Code
    • NodeJS 20.15.1
    • Angular CLI: 16.2.11
    • Node: 22.7.0 (Unsupported)
    • Package Manager: npm 9.5.0
    • Angular: 16.2.12
    • typescript 4.9.5

    Continue reading...

Compartilhe esta Página