Angular 2: Cannot find name 'Subscription'

寵の児 提交于 2021-02-06 14:29:29

问题


When trying to set the type of an attribute I get the error Cannot find name 'Subscription'. From which package do I import it from?

import { Component, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';

// I'm missing an import here. Just don't know which package to load from.

@Component({
  moduleId: module.id,
  selector: 'my-component',
  templateUrl: 'my.component.html',
  styleUrls: ['my.component.css']
})
export class MyComponent implements OnInit, OnDestroy {

  private sub: any;

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

  ngOnInit() {
    this.sub = this.route.params.subscribe(params => {
       let id = +params['id']; // (+) converts string 'id' to a number
     });
  }

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

}

Edit: Provide a more detailed code example.


回答1:


You have to import it like this:

import { Subscription } from 'rxjs';

ORIGINAL ANSWER

import { Subscription } from 'rxjs/Subscription';

Take a look here: https://angular.io/docs/ts/latest/guide/router.html and there are several plunker's linked in that documentation.




回答2:


in angular 6 and angular 7

import { Subscription } from 'rxjs';



回答3:


You have to import Subscription from "rxjs/Rx".

import { Subscription } from "rxjs/Rx";



回答4:


In this case, just that line should load the type

import {Subscription}  from "rxjs/Rx";

And we can use it as expected:

private sub: Subscription;



回答5:


In Angular 9, You can import subscription with the following:

import { Subscription } from 'rxjs/internal/Subscription';


来源:https://stackoverflow.com/questions/38997610/angular-2-cannot-find-name-subscription

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!