diff --git a/packages/schematics/angular/utility/ast-utils.ts b/packages/schematics/angular/utility/ast-utils.ts index 4f6dc3565aab..541786dd8e49 100644 --- a/packages/schematics/angular/utility/ast-utils.ts +++ b/packages/schematics/angular/utility/ast-utils.ts @@ -93,9 +93,11 @@ export function insertImport(source: ts.SourceFile, fileToEdit: string, symbolNa * @param node * @param kind * @param max The maximum number of items to return. + * @param recursive Continue looking for nodes of kind recursive until end + * the last child even when node of kind has been found. * @return all nodes of kind, or [] if none is found */ -export function findNodes(node: ts.Node, kind: ts.SyntaxKind, max = Infinity): ts.Node[] { +export function findNodes(node: ts.Node, kind: ts.SyntaxKind, max = Infinity, recursive = false): ts.Node[] { if (!node || max == 0) { return []; } @@ -105,7 +107,7 @@ export function findNodes(node: ts.Node, kind: ts.SyntaxKind, max = Infinity): t arr.push(node); max--; } - if (max > 0) { + if (max > 0 && (recursive || node.kind !== kind)) { for (const child of node.getChildren()) { findNodes(child, kind, max).forEach(node => { if (max > 0) { diff --git a/packages/schematics/angular/utility/ast-utils_spec.ts b/packages/schematics/angular/utility/ast-utils_spec.ts index 0f82e4acf2d4..bef44d347ee9 100644 --- a/packages/schematics/angular/utility/ast-utils_spec.ts +++ b/packages/schematics/angular/utility/ast-utils_spec.ts @@ -479,6 +479,41 @@ describe('ast utils', () => { ); }); + it('should add a route to the routes to the correct array when having nested object literal', () => { + const moduleContent = ` + import { BrowserModule } from '@angular/platform-browser'; + import { NgModule } from '@angular/core'; + import { AppComponent } from './app.component'; + + const routes = [ + { path: 'foo', component: FooComponent, data: { path: 'test' }} + ]; + + @NgModule({ + declarations: [ + AppComponent + ], + imports: [ + BrowserModule, + RouterModule.forRoot(routes) + ], + bootstrap: [AppComponent] + }) + export class AppModule { } + `; + + const source = getTsSource(modulePath, moduleContent); + const changes = addRouteDeclarationToModule( + source, + './src/app', `{ path: 'bar', component: BarComponent }`, + ); + const output = applyChanges(modulePath, moduleContent, [changes]); + expect(output).toMatch( + // tslint:disable-next-line:max-line-length + /const routes = \[\r?\n?\s*{ path: 'foo', component: FooComponent, data: { path: 'test' }},\r?\n?\s*{ path: 'bar', component: BarComponent }\r?\n?\s*\]/, + ); + }); + it('should add a route to the routes argument of RouteModule', () => { const moduleContent = ` import { BrowserModule } from '@angular/platform-browser';