简体   繁体   中英

ERROR Error: Uncaught (in promise): Error: No provider for ActivatedRoute

package.json dependencies

"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"

}

In component post-show.component.ts I've import 'ActivatedRoute' and use-

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

When I try to use 'ActivatedRoute' it through the error-

ERROR Error: Uncaught (in promise): Error: No provider for ActivatedRoute! Error: No provider for ActivatedRoute!

You need add: providers : [ActivatedRoute], in @Component , like that:

@Component({
   selector: 'post-show',
   templateUrl: 'post-show.component.html',
   styleUrls: ['post-list.component.css'],
   providers: [ ActivatedRoute ]
})

What worked for me was:

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

Then importing RouterTestingModule in the .spec file:

imports: [
    RouterTestingModule,
],

请在您的主模块中导入RouterModule。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM