Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/30.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript angular 2布线需要单击两次以触发ngOnInit_Javascript_Angular_Angular Ui Router_Ngroute - Fatal编程技术网

Javascript angular 2布线需要单击两次以触发ngOnInit

Javascript angular 2布线需要单击两次以触发ngOnInit,javascript,angular,angular-ui-router,ngroute,Javascript,Angular,Angular Ui Router,Ngroute,问题是,在路由中,我必须单击两次才能触发Ngonit代码 奇怪的是,如果我有两条路由:A和B,我先点击A,它只会触发构造函数,如果我在它之后点击B,它会在调用B的构造函数之前触发A的onInit 使用角度2.0.0-rc.4和路线3.0.0-beta.2 页面加载时显示错误: vendors.js:2291 Unhandled promise rejection Error: Cannot match any routes: '' at Observable._subscribe (http:/

问题是,在路由中,我必须单击两次才能触发Ngonit代码

奇怪的是,如果我有两条路由:A和B,我先点击A,它只会触发构造函数,如果我在它之后点击B,它会在调用B的构造函数之前触发A的onInit

使用角度2.0.0-rc.4和路线3.0.0-beta.2

页面加载时显示错误:

vendors.js:2291 Unhandled promise rejection Error: Cannot match any routes: ''
at Observable._subscribe (http://localhost:54037/js/app.js:19280:28)
at Observable.subscribe (http://localhost:54037/js/app.js:56291:60)
at Observable._subscribe (http://localhost:54037/js/app.js:56328:26)
at MergeMapOperator.call (http://localhost:54037/js/app.js:26178:21)
at Observable.subscribe (http://localhost:54037/js/app.js:56291:36)
at Observable._subscribe (http://localhost:54037/js/app.js:56328:26)
at MergeMapOperator.call (http://localhost:54037/js/app.js:26178:21)
at Observable.subscribe (http://localhost:54037/js/app.js:56291:36)
at Observable._subscribe (http://localhost:54037/js/app.js:56328:26)
at MapOperator.call (http://localhost:54037/js/app.js:56831:21)
咽锉

/// <binding Clean='default, clean, resources' />
/*
This file in the main entry point for defining Gulp tasks and using Gulp     plugins.
Click here to learn more. http://go.microsoft.com/fwlink/?LinkId=518007
*/

var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var typescript = require('gulp-typescript');
var systemjsBuilder = require('systemjs-builder');
const del = require("del");

// Compile TypeScript app to JS
gulp.task('compile:ts', function () {
return gulp
  .src([
      "appTS/**/*.ts",
      "typings/*.d.ts"
  ])
  .pipe(sourcemaps.init())
  .pipe(typescript({
      "module": "system",
      "moduleResolution": "node",
      "outDir": "app",
      "target": "ES5"
  }))
  .pipe(sourcemaps.write('.'))
  .pipe(gulp.dest('app'));
});

// Generate systemjs-based bundle (app/app.js)
gulp.task('bundle:app', function () {
var builder = new systemjsBuilder('./', './system.config.js');
return builder.buildStatic('app', 'wwwroot/js/app.js');
});

// Copy and bundle dependencies into one file (vendor/vendors.js)
// system.config.js can also bundled for convenience
gulp.task('bundle:vendor', function () {
return gulp.src([
    'node_modules/core-js/client/shim.min.js',
    'node_modules/systemjs/dist/system-polyfills.js',
    'node_modules/reflect-metadata/Reflect.js',
    'node_modules/zone.js/dist/zone.js',
    'node_modules/systemjs/dist/system.js',
    'system.config.js'
])
    .pipe(concat('vendors.js'))
    .pipe(gulp.dest('build'));
});

// Copy dependencies loaded through SystemJS into dir from node_modules
gulp.task('copy:vendor', function () {
return gulp.src([
    'node_modules/rxjs/bundles/Rx.js',
    'node_modules/@angular/**/*'
])
.pipe(gulp.dest('build'));
});

gulp.task('vendor', ['bundle:vendor', 'copy:vendor']);
gulp.task('app', ['compile:ts', 'bundle:app']);

// Bundle dependencies and app into one file (app.bundle.js)
gulp.task('bundle', ['vendor', 'app'], function () {
return gulp.src([
    'build/app.js',
    'build/vendors.js'
])
.pipe(concat('app.bundle.js'))

.pipe(gulp.dest('wwwroot/js/app'));
});

/**
 * Copy all resources that are not TypeScript files into build directory.
 */
gulp.task("resources", () => {
return gulp.src(["Scripts/app/**/*", "!**/*.ts"])
    .pipe(gulp.dest("wwwroot/app"));
});

/**
 * Remove build directory.
 */
gulp.task('clean', (cb) => {
return del(["build"], cb);
});

gulp.task('default', ['bundle']);
列表组件

import {Component, Inject, OnInit } from '@angular/core';
import 'rxjs/Rx'; 
import {MediaItemComponent} from './media-item.component';
import {CategoryListPipe} from './category-list.pipe';
import {MediaItemService} from './media-item.service';

@Component({
selector: 'media-item-list',
directives: [MediaItemComponent],
pipes: [CategoryListPipe],
providers: [MediaItemService],
templateUrl: 'app/media-item-list.component.html',
styleUrls: ['app/media-item-list.component.css']
})
export class MediaItemListComponent implements OnInit {
mediaItems; 

constructor(private mediaItemService: MediaItemService) {
    console.log("constructor MediaItemList");
}

ngOnInit() {
    console.log("ngOnInit MediaItemList");
    this.getMediaItem();

}

onMediaItemDeleted(mediaItem) {

    this.mediaItemService.delete(mediaItem)
        .subscribe(() => {
            this.getMediaItem();

        });
}

getMediaItem() {

    this.mediaItemService.get().subscribe(mediaitems => {
        this.mediaItems = mediaitems;
    },
        function (error) { console.log("Error happened" + error) },
        function () {
        }
    );
}
}
system.js

// map tells the System loader where to look for things
var map = {
'app': 'Scripts/app',
'rxjs': 'node_modules/rxjs',
'@angular': 'node_modules/@angular'
};

// packages tells the System loader how to load when no filename and/or no         extension
var packages = {
'app': { main: 'main', defaultExtension: 'js' },
'rxjs': { defaultExtension: 'js' },
};

var packageNames = [
  '@angular/common',
  '@angular/compiler',
  '@angular/core',
  '@angular/forms',
  '@angular/http',
  '@angular/platform-browser',
  '@angular/platform-browser-dynamic',
  '@angular/router',
  '@angular/testing',
  '@angular/upgrade',
];

// add package entries for angular packages in the form '@angular/common': {         main: 'index.js', defaultExtension: 'js' }
packageNames.forEach(function (pkgName) {
packages[pkgName] = { main: 'index.js', defaultExtension: 'js' };
});

System.config({
map: map,
packages: packages
});
index.html

<html>
<head>
<title>MeWL</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="/" />
<link href="resets.css" rel="stylesheet">
<script src="js/vendors.js"></script>
<script src="js/app.js"></script>
<style>
    body {
        margin: 0px;
        padding: 0px;
        background-color: #32435b;
    }
</style>
</head>

<body>
<media-tracker-app>Loading...</media-tracker-app>
</body>

</html>
看来

vendors.js:2291未处理的承诺拒绝错误:无法匹配任何路由:“”

导致更改检测无法运行

要避免此错误,请为
'
路径添加路由,如

{ path: '', redirectTo: '/list', pathMatch: 'full' }


我认为更好的答案是在屏幕上添加“OnSameurNavigation”选项

RouterModule.forRoot(
  appRoutes,
  {
    useHash: false,
    anchorScrolling: "enabled",
    onSameUrlNavigation: "reload",
    enableTracing: true,
    scrollPositionRestoration: "enabled"
  })

更新到路由器beta.2怎么样?我已经升级到rc4和beta.2,但仍然存在相同的问题:/您测试了哪些浏览器?这可能与此相关,可能是由于重新加载时出错造成的。请尝试添加路由
{path:'',重定向到:'/list',路径匹配:'full'},
,然后再试一次好吗?非常感谢,这已经解决了问题:D您是一个传奇人物!我在Angular 6.0.3中仍然遇到此问题,控制台中没有任何错误-我必须单击路由链接两次才能从外部服务加载任何数据
    <h2>{{mediaItem.name }}</h2>

    <div>{{mediaItem.category}}</div>
    <div>{{mediaItem.year}}</div>
    <div class="tools">
    <a class="delete" (click)="onDelete()">
    remove
    </a>
    <a class="details">
    watch
    </a>
    </div>
import {Component, Input, Output, EventEmitter} from '@angular/core';
import {FavoriteDirective} from './favorite.directive';



@Component({
selector: 'media-item',
directives: [FavoriteDirective],
templateUrl: 'app/media-item.component.html',
styleUrls: ['app/media-item.component.css']
})
export class MediaItemComponent {

@Input('mediaItemToWatch') mediaItem;
@Output('deleted') delete = new EventEmitter();
onDelete() {
    this.delete.emit(this.mediaItem);
}
}
{ path: '', redirectTo: '/list', pathMatch: 'full' }
{ path: '', component: DummyComponent, pathMatch: 'full' }
RouterModule.forRoot(
  appRoutes,
  {
    useHash: false,
    anchorScrolling: "enabled",
    onSameUrlNavigation: "reload",
    enableTracing: true,
    scrollPositionRestoration: "enabled"
  })