嗨,我需要从路由模块访问某个组件中存在的某些数据。我正在尝试为参数设置默认值,但我不知道如何将服务注入路由模块中。
路由模块->
import { NgModule } from '@angular/core';
import {Routes,RouterModule} from '@angular/router'
import {SuperbarComponent} from './superbar/superbar.component'
import { FeedComponent } from './feed/feed.component';
import {DatashareService} from '../datashare.service'
const st1 :string = 'hello'; //this need to be fetched from service
const st2 :sting = 'world'; //to set as default redrect
const routes : Routes = [
{path : ':su/:cat', component : FeedComponent},
{path : '', redirectTo : st1+''+st2, pathMatch : 'full'}
]
@NgModule({
imports : [RouterModule.forRoot(routes),],
exports: [RouterModule,]
})
export class AppRoutingModule { }
在这里,我需要使用该服务将str1,str2初始化为需要输入到url中的适当值。 我的小服务->
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DatashareService {
supercategory : string;
category :string;
constructor() { }
getdata(su : string, cat :string){
this.supercategory = su;
this.category = cat;
}
setcategory(){
return this.category;
}
setsupercategory(){
return this.supercategory;
}
}
还有我从中感染数据的地方
import { Component, OnInit, ViewChild } from '@angular/core';
import {Http} from '@angular/http';
import {MetadataService } from '../metadata.service';
import {Tag, CatJson} from '../meta-data-model';
import {CatbarComponent} from '../catbar/catbar.component';
import {DatashareService} from '../datashare.service'
@Component({
selector: 'app-superbar',
templateUrl: './superbar.component.html',
styleUrls: ['./superbar.component.css']
})
export class SuperbarComponent implements OnInit {
@ViewChild('child1')
private child1 : CatbarComponent
supermap = new Map();
isloggedin : boolean = true;
isloading : boolean = true;
supercategories : Tag [] = [];
allcategories : Tag[] = [];
categories : Tag[] = [];
tempCategories : Tag[] = [];
selectedsu : Tag;
constructor(private meta : MetadataService,private urlset : DatashareService) {}
//using meta data service to get supercategories
ngOnInit() {
this.meta.getmetadata().subscribe(response =>{
//newCatJson requires an object type data
//in earlier versions one needed to body.parse(), but since http returns an object
//that no longer needs be done
const data = new CatJson(response);
this.supercategories = data.superCat;
this.selectedsu = this.supercategories[0];
this.allcategories = data.allCat;
this.createsupermap();
this.categories = this.supermap.get(this.selectedsu);
this.urlset.getdata(this.selectedsu.superCategory,this.supermap.get(this.selectedsu)[0]['category']);
this.isloading = false;
});
}