我一直在玩Angular2很长一段时间。所有的代码都是前沿并使用最新的TypeScript Nightly 1.6和Angular alpha 34.我无法从其中一个组件调用父路由器。请尽可能帮助我。因此,我附加了导航尝试的代码和错误。
app.ts
/// <reference path="../typings/angular2/angular2.d.ts" />
'use strict';
import {Component, View, bootstrap} from 'angular2/angular2';
import {routerInjectables, RouterOutlet, RouteConfig} from 'angular2/router';
import {LoginApp} from './login/login';
import {DashboardApp} from './dashboard/dashboard';
// Annotation section
@Component({
selector: 'inventman-app'
})
@View({
template: `<!-- The router-outlet displays the template for the current component based on the URL -->
<router-outlet></router-outlet>`,
directives: [RouterOutlet]
})
@RouteConfig([
{ path: '/', redirectTo: '/login' },
{ path: '/dashboard', as: 'dashboard', component: DashboardApp },
{ path: '/login', as: 'login', component: LoginApp }
])
// Component controller
export class InventmanApp {
constructor() {
}
}
// bootstrap the Main App
bootstrap(InventmanApp,
[
routerInjectables
]);
login.ts
/// <reference path="../../typings/angular2/angular2.d.ts" />
'use strict';
import {Component, View, formDirectives} from 'angular2/angular2';
import {Router} from 'angular2/router';
import {HttpService} from '../../services/httpservice/httpservice';
@Component({
selector: 'login-app'
})
@View({
templateUrl: './jsts/components/login/login.html',
directives: [formDirectives],
styleUrls: ['./jsts/components/login/login.css']
})
export class LoginApp {
username: String;
password: String;
constructor(public router: Router) {
}
onSubmit() {
const username = this.username, password = this.password;
HttpService.serve('https://' + location.host + '/userapi/sessions/create', 'POST', {
'Accept': 'application/json',
'Content-Type': 'application/json'
}, JSON.stringify({ username, password }))
.then(response=> {
if (!response.id_token) {
// Alerts the actual message received from the server
alert(response.message);
// Removes any previous assigned JWT to ensure tighter security
localStorage.removeItem('jwt');
}
else {
// Valid Login attempt -> Assign a jwt to the localStorage
localStorage.setItem('jwt', response.id_token);
// route to the dashboard
this.router.parent.navigate('/dashboard');
}
});
}
}
错误
EXCEPTION:TypeError:无法读取属性&#39; parent&#39;未定义的 angular2.dev.js:22448 STACKTRACE:angular2.dev.js:22448 TypeError: 无法阅读财产&#39;父母&#39;未定义的 在eval(login.js:34) 在Zone.run(angular2.dev.js:136) 在Zone.execute。$ __ 3._createInnerZone.zone.fork.fork。$ run [as run](angular2.dev.js:16437) 在zoneBoundFn(angular2.dev.js:109) 在lib $ es6 $ promise $$ internal $$ tryCatch(angular2.dev.js:1359) 在lib $ es6 $ promise $$ internal $$ invokeCallback(angular2.dev.js:1371) 在lib $ es6 $ promise $$ internal $$ publish(angular2.dev.js:1342) 在angular2.dev.js:187 在Zone.run(angular2.dev.js:136) 在zoneBoundFn(angular2.dev.js:109)
答案 0 :(得分:3)
问题的答案非常简单。不知怎的,从cli运行时新的beta typescript编译器似乎完全避免了角度的DI。从IDE(Sublime 3)插件进行编译似乎解决了这个问题。
我已经进一步改进了代码,应该很快将其推送到GIT,以便其他人参考并使用。