错误错误:未捕获(在承诺中):错误:没有ActivatedRoute的提供者

时间:2017-07-12 13:29:14

标签: angular angular2-routing

package.json依赖项

"dependencies": {
"@angular/cli": "1.0.0",
"@angular/compiler-cli": "^4.0.0",
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/router": "^4.0.0",
"core-js": "^2.4.1",
"rxjs": "^5.1.0",
"zone.js": "^0.8.4"

}

在组件post-show.component.ts中我导入'ActivatedRoute'并使用 -

import {Component, OnInit, Input } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Post } from './post';
import { PostService } from './post.service';

@Component({
    selector: 'post-show',
    templateUrl: 'post-show.component.html',
    styleUrls: ['post-list.component.css']
})
export class PostShowComponent implements OnInit {
    id: number;
    routerId: any;

    constructor(private http: Http, private route: ActivatedRoute, private postService: PostService ) {}

    @Input() post: Post;

    ngOnInit(){
        this.routerId = this.route.params.subscribe(
        params => {
            this.id = +params['id'];
        })
        let postRequest = this.route.params
            .flatMap((params: Params) => 
                this.postService.getPost(+params['id']));
        postRequest.subscribe(response => this.post = response.json());
    }
}

当我尝试使用'ActivatedRoute'时,错误 -

  

错误错误:未捕获(承诺):错误:没有ActivatedRoute的提供者!   错误:没有ActivatedRoute的提供者!

3 个答案:

答案 0 :(得分:2)

您需要添加: 提供商:[ActivatedRoute],在 @Component 中,如下所示:

<ul class="rlist--inline">
  <li class="menu-item"><a><span>Topics</span></a></li>
  <li class="dropdown menu-parent">
    <a title="Journal" class="dropdown__toggle">
      <span>Journal</span>
    </a>
    <ul class="rlist dropdown__menu">
      <li>
        <a title="Current Issue">
          <span>Current Issue</span>
        </a>
      </li>
      <li>
        <a>
          <span>Archive</span>
        </a>
      </li>
      <li>
        <a>
          <span>Article Series</span>
        </a>
      </li>
    </ul>
  </li>
</ul>

答案 1 :(得分:1)

对我有用的是:

import { RouterTestingModule } from '@angular/router/testing';

然后在RouterTestingModule文件中导入.spec

imports: [
    RouterTestingModule,
],

答案 2 :(得分:0)

请在主模块中导入RouterModule。