Generic type Subject<T> requires 1 type argument(s). - Angular

32,895

Solution 1

The Subject class has a generic type parameter in TypeScript. This means, that instances of this class can only be created by passing an additional type parameter, like this:

private ngUnsubscribe: Subject<MyClass> = new Subject();

Solution 2

Add a generic type for subject

private ngUnsubscribe: Subject<any> = new Subject();
Share:
32,895
Roxy'Pro
Author by

Roxy'Pro

Updated on July 05, 2022

Comments

  • Roxy'Pro
    Roxy'Pro almost 2 years

    I'm getting data from my service and I've red about it's important to unsubscribe after subscribe, and here is how I did it:

    export class RItemComponent implements OnInit {
    
        apiPath = environment.apiUrl;
        private ngUnsubscribe: Subject = new Subject();
    
        constructor(private _sharedService: SharedService) { }
    
        rItems: Product[];
    
        ngOnInit() {
        this._sharedService.
            getReceiptItem().takeUntil(this.ngUnsubscribe).
            subscribe(products => this.rItems = products);
        }
    
        ngOnDestroy() {
        this.ngUnsubscribe.next();
        this.ngUnsubscribe.complete();
        }
    }
    

    But now I'm getting an error:

    Generic type Subject<T> requires 1 type argument(s). subscribe
    

    I don't understand why?

    Any kind of help would be awesome, thanks!

  • ggradnig
    ggradnig almost 6 years
    You're welcome :-) There are books written about ReactiveX, but good starting point is the following: reactivex.io/documentation/subject.html. Concerning generic type parameters, have a look at the TypeScript doc: typescriptlang.org/docs/handbook/generics.html
  • GreeneCreations
    GreeneCreations over 5 years
    any is discouraged. There's almost always a more accurate type. If you really don't know or can't know what the type will be, then consider using the new type unknown. typescriptlang.org/docs/handbook/release-notes/…