Angular 2:找不到姓名'订阅'

时间:2016-08-17 13:09:50

标签: angular typescript rxjs

尝试设置属性类型时,我收到错误Cannot find name 'Subscription'。我从哪个包中导入它?

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();
  }

}

修改:提供更详细的代码示例。

5 个答案:

答案 0 :(得分:48)

你必须像这样导入它:

fstream

编辑 Angular 6

import { Subscription } from 'rxjs/Subscription';

看看这里:https://angular.io/docs/ts/latest/guide/router.html 并且该文档中有几个关联者。

答案 1 :(得分:9)

以角度6和角度7

import { Subscription } from 'rxjs';

答案 2 :(得分:5)

您必须从“ rxjs / Rx ”导入订阅

import { Subscription } from "rxjs/Rx";

答案 3 :(得分:5)

在这种情况下,只需该行加载类型

import {Subscription}  from "rxjs/Rx";

我们可以按预期使用它:

private sub: Subscription;

答案 4 :(得分:0)

您可以使用以下内容导入订阅

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