0%

angular error 筆記

 

最近搞 angular 把遇到的錯誤筆記一下 , 怕又忘了

implicitly has an ‘any’ type

https://stackoverflow.com/questions/43064221/typescript-ts7006-parameter-xxx-implicitly-has-an-any-type

In your tsconfig.json file set the parameter “noImplicitAny”: false under compilerOptions to get rid of this error.

Can’t bind to ‘pa-attr’ since it isn’t a known property of ‘td’

解法設定 tsconfig.json 內的屬性 "strictTemplates": false

1
2
3
4
5
6
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": false
}

error TS2322: Type ‘null’ is not assignable to type ‘{ [key: string]: any; }’

解法
加上 | null 即可

1
return (control:FormControl) : {[key: string]: any} | null => {

error TS2322: Type ‘Product | undefined’ is not assignable to type ‘Product’.

解法 1
加上驚嘆號騙他一定有值

1
2
3
getProduct(id: number): Product {
return this.products.find(p => this.locator(p, id))!;
}

解法 2
加上型別

1
return <Product>this.products.find(p => this.locator(p, id));

解法 3
加上 undefined

1
2
3
getProduct(id: number): Product | undefined {
return this.products.find(p => this.locator(p, id));
}

error TS2345: Argument of type ‘number | undefined’ is not assignable to parameter of type ‘number’

解法
加上型別 <number>

1
2
3
4
5
6
7
8
9
10
saveProduct(product: Product) {
if (product.id == 0 || product.id == null) {
product.id = this.generateID();
this.products.push(product);
} else {
let index = this.products
.findIndex(p => this.locator(p, <number>product.id));
this.products.splice(index, 1, product);
}
}

Object is possibly ‘undefined’

解法
都加上 ? 運算子即可

1
2
3
4
swapProduct() {
let p = this.products.shift();
this.products.push(new Product(p?.id, p?.name, p?.category, p?.price));
}

或是多一個防止 null 的判斷式

1
2
3
4
swapProduct() {
let p = this.products.shift();
if(p != null) this.products.push(new Product(p.id, p.name, p.category, p.price));
}

Can’t bind to ‘pa-attr’ since it isn’t a known property of ‘td’.

解法要加上 @Input("pa-attr")

1
2
3
4
5
6
7
8
9
10
11
12
13
import {Directive, ElementRef, Attribute, Input} from "@angular/core";

@Directive({
selector: "[pa-attr]",
})
export class PaAttrDirective{
@Input("pa-attr")
bgClass!: string;

constructor(element: ElementRef , @Attribute("pa-attr") bgClass: string) {
element.nativeElement.classList.add(bgClass || "bg-success" , "text-white");
}
}

error TS7006: Parameter ‘$event’ implicitly has an ‘any’ type

解法
加上 any 或是 MouseEvent 即可
html

1
<button class="btn btn-sm btn-primary" (click)="search($event)">Search</button>

ts

1
2
3
4
5
6
7
search(event:any){
alert(event)
}

search(event:MouseEvent){
alert(event)
}

Type ‘Event’ is not assignable to type ‘string’.

app.module.ts 加入 FormsModule 即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { HeaderComponent } from './header/header.component';
import { FooterComponent } from './footer/footer.component';
import { ArticlesComponent } from './articles/articles.component';
import { TagsComponent } from './tags/tags.component';
import { FormsModule } from '@angular/forms';

@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
ArticlesComponent,
TagsComponent
],
imports: [
BrowserModule ,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})

‘Output’ accepts too few arguments to be used as a decorator here. Did you mean to call it first and write ‘@Output()’

解法 Output 忘了加括號
另外常常會遇到 EventEmitter import 錯誤
因為 EventEmitter 會有好幾個 namespace 都有 , 一般情況下注意要 import angular/core 的才正確

1
2
@Output()
keywordchange = new EventEmitter<string>();

error TS2729: Property ‘originalList’ is used before its initialization

解法
因為 ts 是有順序性的限制讓 originalList 放在前面即可

1
2
originalList : any[] = [{name : "test"}];
list = this.originalList;

NullInjectorError: R3InjectorError(AppModule)[ProductService -> StaticDataSource -> StaticDataSource -> StaticDataSource]: NullInjectorError: No provider for StaticDataSource!

看書遇到的錯誤 , 好像舊版只要寫 @Injectable() 就收工了 , 新版要補 providedIn: 'root' 參考這篇

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { Injectable } from "@angular/core";
import { Product } from "./product.model";
import { Observable, from } from "rxjs";

//@Injectable()
@Injectable({
providedIn: 'root'
})
export class StaticDataSource {
private products: Product[] = [
new Product(1, "Product 1", "Category 1", "Product 1 (Category 1)", 100),
new Product(2, "Product 2", "Category 1", "Product 2 (Category 1)", 100),
new Product(3, "Product 3", "Category 1", "Product 3 (Category 1)", 100),
new Product(4, "Product 4", "Category 1", "Product 4 (Category 1)", 100),
];

getProducts(): Observable<Product[]>{
return from([this.products])
}
}

Type ‘string’ is not assignable to type ‘LoadChildrenCallback’.ts(2322)

錯誤大概是這句

1
loadChildren: "./admin/admin.module#AdminModule",

要改下面這樣

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { StoreFirstGuard } from './storeFirst.guard';
import { CheckoutComponent } from './store/checkout.component';
import { CartDetailComponent } from './store/cartDetail.component';
import { StoreComponent } from './store/store.component';
import { RouterModule } from '@angular/router';
import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { AppComponent } from "./app.component";
import { StoreModule } from "./store/store.module";

@NgModule({
imports: [BrowserModule, StoreModule,
RouterModule.forRoot([
{ path: "store", component: StoreComponent, canActivate: [StoreFirstGuard] },
{ path: "cart", component: CartDetailComponent, canActivate: [StoreFirstGuard] },
{ path: "checkout", component: CheckoutComponent, canActivate: [StoreFirstGuard] },
{
path: "admin",
//錯誤
//loadChildren: "./admin/admin.module#AdminModule",

//正確
loadChildren: () => import("./admin/admin.module")
.then(m => m.AdminModule),
canActivate: [StoreFirstGuard]
},
{ path: "**", redirectTo: "/store" }
])],
providers: [StoreFirstGuard],
declarations: [AppComponent],
bootstrap: [AppComponent]
})
export class AppModule { }
關閉