How can I ensure I am receiving real-time updates from a Resolver Service by subscribing and staying in sync with the

How can I effectively implement this code without encountering an error?

"Property 'resolve' in type 'DocumentaryResolverService' is not assignable to the same property in base type 'Resolve'."

import { Documentary } from './../models/documentary.model';
import { DocumentaryService } from './documentary.service';
import { Injectable } from '@angular/core';
import {
  Resolve,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';

@Injectable({ providedIn: 'root' })
export class DocumentaryResolverService implements Resolve<Documentary> {
  constructor(private documentaryService: DocumentaryService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    let slug = route.params['slug'];
    let documentary: Documentary;
    return this.documentaryService.get(slug).subscribe(result => {
        documentary = <Documentary> result;
        return documentary;
    });
  }
}

When I adjust the code as follows, the error disappears. However, I would like to ensure that the subscription to the observable completes before returning the documentary.

import { Documentary } from './../models/documentary.model';
import { DocumentaryService } from './documentary.service';
import { Injectable } from '@angular/core';
import {
  Resolve,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';

@Injectable({ providedIn: 'root' })
export class DocumentaryResolverService implements Resolve<Documentary> {
  constructor(private documentaryService: DocumentaryService) {}

  resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    let slug = route.params['slug'];
    let documentary: Documentary;
    this.documentaryService.get(slug).subscribe(result => {
        documentary = <Documentary> result;
    });
    return documentary;
  }
}

Implementing async and await did not yield the desired outcome for me

import { Documentary } from './../models/documentary.model';
import { DocumentaryService } from './documentary.service';
import { Injectable } from '@angular/core';
import {
  Resolve,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from '@angular/router';

@Injectable({ providedIn: 'root' })
export class DocumentaryResolverService implements Resolve<Documentary> {
  constructor(private documentaryService: DocumentaryService) {}

  async resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
    let slug = route.params['slug'];
    console.log(slug);
    console.log("resolver");
    let documentary: Documentary;
    await this.documentaryService.get(slug).subscribe(result => {
        return <Documentary> result;
    });
    return documentary;
  }
}

The resolver function is invoked within this component:

import { DocumentaryService } from './../../../services/documentary.service';
import { Documentary } from './../../../models/documentary.model';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute, Router, Params } from '@angular/router';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-admin-documentary-detail',
  templateUrl: './admin-documentary-detail.component.html',
  styleUrls: ['./admin-documentary-detail.component.css']
})
export class AdminDocumentaryDetailComponent implements OnInit, OnDestroy {
  documentary: any;
  slug: string;
  documentarySubscription: Subscription;

  constructor(
    private documentaryService: DocumentaryService,
    private route: ActivatedRoute,
    private router: Router) { }

  ngOnInit() {
    this.route.data.subscribe(data => {
      this.documentary = data;
      console.log(this.route.data);
    })
    }

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

Answer №1

After subscribing to the service and retrieving the data, it transforms from an Observable to a Subscription object. Your "resolve" function should return either a Documentary, Observale<Documentary>, or Promise<Documentary>.

Instead of subscribing directly, simply return the Observable like this:

return this.documentaryService.get(slug);

For more information on the Resolver API, you can visit: https://angular.io/api/router/Resolve

Answer №2

In order to obtain the necessary resolve data, you must include it in your AdminDocumentaryDetailComponent route.

const routes: Routes = [
  {
    path: '',
    component: AdminDocumentaryDetailComponent,
    resolve: {
       documentary: DocumentaryResolverService
    }
  }
];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Executing TypeDoc on a Windows system results in zero files being created and no error messages reported

I have been working on generating documentation for a JavaScript application using TypeDoc. Unfortunately, I am facing an issue where TypeDoc is not outputting any files or errors. To get started, I installed TypeDoc within the project folder: npm instal ...

The Typescript compiler is throwing an error in a JavaScript file, stating that "type aliases can only be used in a .ts file."

After transitioning a react js project to react js with typescript, I made sure to move all the code to the typescript react app and added types for every necessary library. In this process, I encountered an issue with a file called HeatLayer.js, which is ...

Validator returns undefined when expressing invalid data

Having an issue with validation, here is the code snippet: routes.js var express = require('express'); var router = express.Router(); var hello_controller = require('../api/controllers/helloController'); var { validationRules, validat ...

How do I implement a click event in an item list using Angular 5?

As a novice student delving into Angular 5, I am faced with an issue that may also arise in Angular 2. Currently, I am working on a project where I need to implement a basic search input feature. The idea is to allow users to type in the name of a city an ...

Subscribing to an RxJs Subject and receiving multiple values

In my Angular Service, there is a Subject defined like this: private sub = new Subject(); sendSub(page: page) { this.sub.next(page); } getSub(): Observable<any> { return this.sub.asObservable(); } In the parent component, I have subscribe ...

Tips for changing the name of a directory in an Angular 6 application

Looking for guidance on renaming a folder in an Angular 6 project's components directory. Is there a safe way to do this without causing any issues, or is it as simple as just changing the name of the folder? Using Visual Studio Code as my IDE. ...

Challenges with CORS while Angular application is making a POST request to an ASP .Net API

I am currently working on developing an Angular application that will make HTTP requests to an ASP.NET API. Here is the request I am sending from Angular (hosted on http://localhost:4200): httpOptions = { headers: new HttpHeaders({ 'Conte ...

Sending Json data using HTTP POST

I am facing an issue with posting my JSON values in a nested format. Currently, my data is being submitted singularly due to constraints in the database. I need to select multiple doctors from my phone app and save them in a nested format when clicking &ap ...

Issue with displaying MP4 movies in Angular

I'm trying to display an mp4 video in Angular 9: <video controls (click)="toggleVideo()" preload="none" *ngIf="post.moviePath != null" #videoPlayer> <source [src]="getMovieSanitazePath(post.moviePath ...

Error encountered while utilizing the Extract function to refine a union

I am currently working on refining the return type of my EthereumViewModel.getCoinWithBalance method by utilizing the Extract utility type to extract a portion of my FlatAssetWithBalance union based on the generic type C defined in EthereumViewModel (which ...

How can you update ngModel in Angular and mark the form as dirty or invalid programmatically?

My form is connected to a model as shown below In the component file: myTextModel: string; updateMyTextModel(): void { this.myTextModel = "updated model value"; //todo- set form dirty (or invalid or touched) here } Html template: <form #test ...

A guide on utilizing the useEffect hook to dynamically update a button icon when hovering over it in a React application

Is it possible to change the icon on a button when hovering using useEffect? <Button style={{ backgroundColor: "transparent" }} type="primary" icon={<img src={plusCart} />} onCl ...

Is there a way for me to pass the templateUrl data from the parent component to another component

Currently, I am in the process of learning Angular2 and facing a situation where I have a dropdown that appears on multiple pages. Each time it is called, the contents of the dropdown change, but the structure remains the same. This is why I have set it up ...

Ionic app experiencing a CORS dilemma post-build

Using Ionic 3, I have written a provider code to fetch data from an API endpoint hosted on an HTTPS server. For example, my endpoint is located at . Below is the code for my provider: // Provider Class Function load(){ if(this.data){ return Pro ...

How can you effectively declare a computed getter in MobX that aggregates an observable list?

Within my project, I have a class hierarchy consisting of projects, task lists, and tasks. Each array is marked as @observable. Now, I am looking to create a "@computed get allTasks" function within the project class that aggregates all tasks from all task ...

One potential solution for fixing the error in GetRepository of TypeORM is to check for undefined properties before attempting to access them. This error typically occurs when trying to read properties of an undefined

[Nest] 171 - 08/31/2022, 8:35:42 PM ERROR [ExceptionHandler] Cannot read properties of undefined (reading 'getRepository') tenant-node | TypeError: Cannot read properties of undefined (reading 'getRepository') tenant-node | at Instance ...

"Exploring the dynamic duo of Angular2 and ng2Material

I am currently facing an issue with the styling in my code while using ng2Material with Angular2. First: A demonstration of Material style functioning properly can be seen in this plunker. When you click on the button, you will notice an animation effect. ...

Experience the power of React TypeScript where functions are passed as props, but access is restricted

Currently, I am working on creating a toggle button using react and typescript. In order to challenge myself, I have decided to pass a function as a prop to a child component to implement a complex feature. From what I remember, utilizing 'this.props& ...

Utilizing Visual Studio Code for setting breakpoints in Typescript Jasmine tests

Currently, I am in the process of configuring a launch setup in Visual Studio Code for debugging my unit tests. The unit tests are written in Typescript, and both the tests and the corresponding code are compiled into a single js file with a source map. ...

What limitations prevent me from utilizing a switch statement to refine class types in Typescript?

Unique Playground Link with Comments This is a standard illustration of type narrowing through the use of interfaces. // Defining 2 types of entities enum EntityType { ANIMAL = 'ANIMAL', PLANT = 'PLANT', } // The interface for ani ...