【问题标题】:Angular 2: Cannot find name 'Subscription'Angular 2:找不到名称“订阅”
【发布时间】:2016-12-24 04:03:39
【问题描述】:

尝试设置属性的类型时,我收到错误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();
  }

}

编辑:提供更详细的代码示例。

【问题讨论】:

  • 我正在关注 Angular 2 文档。他们经常遗漏用户必须研究并浪费大量时间的关键信息——这很烦人。如果有帮助,我可以编写一个示例组件。给我一秒钟。

标签: angular typescript rxjs


【解决方案1】:

在 Angular 9 中,您可以使用以下方式导入订阅:

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

【讨论】:

    【解决方案2】:

    你必须像这样导入它:

    import { Subscription } from 'rxjs';
    

    原始答案

    import { Subscription } from 'rxjs/Subscription';
    

    看这里:https://angular.io/docs/ts/latest/guide/router.html 并且该文档中有几个 plunker 的链接。

    【讨论】:

      【解决方案3】:

      在角度 6 和角度 7 中

      import { Subscription } from 'rxjs';
      

      【讨论】:

        【解决方案4】:

        在这种情况下,只有那一行应该加载类型

        import {Subscription}  from "rxjs/Rx";
        

        我们可以按预期使用它:

        private sub: Subscription;
        

        【讨论】:

          【解决方案5】:

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

          import { Subscription } from "rxjs/Rx";
          

          【讨论】:

            猜你喜欢
            • 2016-10-09
            • 2018-07-31
            • 1970-01-01
            • 2022-01-23
            • 2017-09-07
            • 1970-01-01
            • 2017-03-25
            • 2017-02-21
            • 1970-01-01
            相关资源
            最近更新 更多