导入不在课堂上被识别

时间:2018-01-15 03:33:59

标签: typescript angular2-routing

---src
   |___app
       |___add-property
           |___add-property.component.ts (where error is found)
       |___services
           |___add-property.service.ts
   app-routing.ts

(添加文件树以供参考)

import { Property } from '../models/Property';
import { AddPropertyService } from '../services/addProperty.service';
import { Routing } from '../app-routing';

export class AddPropertyComponent implements OnInit {

  private newProperty :Property;
  *** private routing :Routing; *** issue is right here

  constructor(private addPropertyService: AddPropertyService) { }
  this.routing.doSomething();
}

我的目标是在此代码块的底部调用this.routing.doSomething。代码的一部分我突出显示了问题的位置 - 错误是

Cannot find name 'Routing'.

我也从文件中导出路由(我的路由所在的位置)。

import { Routes, RouterModule } from '@angular/router';

const APP_ROUTES: Routes = [
  { path: '', redirectTo: '/properties', pathMatch: 'full' },
];
export const Routing = RouterModule.forRoot(APP_ROUTES);

有谁知道为什么它找不到名称'路由'即使我相信我正在做的一切正确?

*******我已经解决了,下面将回答未来的参考*******

我遵循了Angular'路由' DOC:

1. I created a app-routing.module.ts and deleted my app-routing.ts
2. Export AppRoutingModule within app-routing.module.ts
3. Import AppRoutingModule into component that was in need of routing (add-
   property.component.ts in my question)
4. Also Import Router module from '@angular/router'
5. Inside component constructor --> add private router: Router
6. this.router.navigate() is now available for use

1 个答案:

答案 0 :(得分:0)

你有:

import { Routing } from '../app-routing';

应该是:

import { Routing } from '../../../app-routing';

<强>更新

似乎路径在正确的位置(见注释)。

另一件事可能是您使用Routing作为Type。 如果您想将其用作Type,则其类型应为ModuleWithProviders

试试这个:

private routing = Routing;

这也应该有效:

private routing: ModuleWithProviders = Routing;

文档:

如果您想拥有doSomething()功能,则需要将导出更改为其他内容:

export const ROUTING = { routing: RouterModule.forRoot(APP_ROUTES), doSomething: () => { // just do something } }

使用classinterface来保存这些值是一种更好的做法,你想要输入所有内容,如果你不打算那就是打字稿的价格遵循这一原则,您将在任何地方以any声明结束。