Wątek przeniesiony 2023-10-13 14:24 z JavaScript przez Riddle.

Problem z importem biblioteki NX Angular

0

Witam wszystkich.
Bardzo proszę o pomoc.
Jestem w trakcie poznawania Nx, a w ramach tego współtworzę projekt eshopu (MEAN) żeby mieć co pokazać na rozmowie jaki Junior.
Projekt znajduje się pod adresem: https://github.com/terabajt/myShop-MEAN-Full-Stack-FRONTEND
Chodzi o to, że jestem na etapie implementacji karty zamówienia. Aplikacja 'eshop' działa prawidłowo - jednak jak próbuję wstrzyknąć do komponentu ProductItemComponent (myShop-MEAN-Full-Stack-FRONTEND/libs/products/src/lib/components/product-item/product-item.component.ts) bibliotekę orders (ponieważ jest tam CartService (libs/orders/src/lib/services/cart.service.ts) ) w konstruktorze w sposób:

import { Component, Input } from '@angular/core';
import { Product } from '../../models/product';
import { CartService } from '@webappshop/orders';

@Component({
    selector: 'products-product-item',
    templateUrl: './product-item.component.html',
    styles: []
})
export class ProductItemComponent {
    @Input()
    product!: Product;

    constructor(private cartService: CartService) {}

    onAddProductToCart() {
    //TUTAJ UŻYJĘ cartService
    }
}

po zapisywaniu projektu dostaję burzę błędów:

Error: libs/orders/src/lib/services/cart.service.ts:17:39 - error TS2345: Argument of type 'string | null' is not assignable to parameter of type 'string'.
  Type 'null' is not assignable to type 'string'.

17         const cart: Cart = JSON.parse(localStorage.getItem(CART_KEY));
                                         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


Error: libs/orders/src/lib/services/cart.service.ts:18:18 - error TS2339: Property 'item' does not exist on type 'CartItem'.

18         cartItem.item.push(cartItem);
                    ~~~~


Error: libs/users/src/lib/pages/login/login.component.html:17:39 - error TS4111: Property 'email' comes from an index signature, so it must be accessed with ['email'].

17               <small *ngIf="loginForm.email.invalid && loginForm.email.dirty" class="error">
                                         ~~~~~

  libs/users/src/lib/pages/login/login.component.ts:11:18
    11     templateUrl: './login.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component LoginComponent.


Error: libs/users/src/lib/pages/login/login.component.html:17:66 - error TS4111: Property 'email' comes from an index signature, so it must be accessed with ['email'].

17               <small *ngIf="loginForm.email.invalid && loginForm.email.dirty" class="error">
                                                                    ~~~~~

  libs/users/src/lib/pages/login/login.component.ts:11:18
    11     templateUrl: './login.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component LoginComponent.


Error: libs/users/src/lib/pages/login/login.component.html:18:40 - error TS4111: Property 'email' comes from an index signature, so it must be accessed with ['email'].

18                 <span *ngIf="loginForm.email.errors.required">Email is required.</span>
                                          ~~~~~

  libs/users/src/lib/pages/login/login.component.ts:11:18
    11     templateUrl: './login.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component LoginComponent.


Error: libs/users/src/lib/pages/login/login.component.html:18:53 - error TS2531: Object is possibly 'null'.

18                 <span *ngIf="loginForm.email.errors.required">Email is required.</span>
                                                       ~~~~~~~~

  libs/users/src/lib/pages/login/login.component.ts:11:18
    11     templateUrl: './login.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component LoginComponent.


Error: libs/users/src/lib/pages/login/login.component.html:18:53 - error TS4111: Property 'required' comes from an index signature, so it must be accessed with ['required'].

18                 <span *ngIf="loginForm.email.errors.required">Email is required.</span>
                                                       ~~~~~~~~

  libs/users/src/lib/pages/login/login.component.ts:11:18
    11     templateUrl: './login.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component LoginComponent.


Error: libs/users/src/lib/pages/login/login.component.html:19:40 - error TS4111: Property 'email' comes from an index signature, so it must be accessed with ['email'].

19                 <span *ngIf="loginForm.email.errors.email">Email is invalid.</span>
                                          ~~~~~

  libs/users/src/lib/pages/login/login.component.ts:11:18
    11     templateUrl: './login.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component LoginComponent.


Error: libs/users/src/lib/pages/login/login.component.html:19:53 - error TS2531: Object is possibly 'null'.

19                 <span *ngIf="loginForm.email.errors.email">Email is invalid.</span>
                                                       ~~~~~

  libs/users/src/lib/pages/login/login.component.ts:11:18
    11     templateUrl: './login.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component LoginComponent.


Error: libs/users/src/lib/pages/login/login.component.html:19:53 - error TS4111: Property 'email' comes from an index signature, so it must be accessed with ['email'].

19                 <span *ngIf="loginForm.email.errors.email">Email is invalid.</span>
                                                       ~~~~~

  libs/users/src/lib/pages/login/login.component.ts:11:18
    11     templateUrl: './login.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component LoginComponent.


Error: libs/users/src/lib/pages/login/login.component.html:27:39 - error TS4111: Property 'password' comes from an index signature, so it must be accessed with ['password'].

27               <small *ngIf="loginForm.password.invalid && loginForm.password.dirty" class="error">
                                         ~~~~~~~~

  libs/users/src/lib/pages/login/login.component.ts:11:18
    11     templateUrl: './login.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component LoginComponent.


Error: libs/users/src/lib/pages/login/login.component.html:27:69 - error TS4111: Property 'password' comes from an index signature, so it must be accessed with ['password'].

27               <small *ngIf="loginForm.password.invalid && loginForm.password.dirty" class="error">
                                                                       ~~~~~~~~

  libs/users/src/lib/pages/login/login.component.ts:11:18
    11     templateUrl: './login.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component LoginComponent.


Error: libs/users/src/lib/pages/login/login.component.html:28:40 - error TS4111: Property 'password' comes from an index signature, so it must be accessed with ['password'].

28                 <span *ngIf="loginForm.password.errors.required">Password is required.</span>
                                          ~~~~~~~~

  libs/users/src/lib/pages/login/login.component.ts:11:18
    11     templateUrl: './login.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component LoginComponent.


Error: libs/users/src/lib/pages/login/login.component.html:28:56 - error TS2531: Object is possibly 'null'.

28                 <span *ngIf="loginForm.password.errors.required">Password is required.</span>
                                                          ~~~~~~~~

  libs/users/src/lib/pages/login/login.component.ts:11:18
    11     templateUrl: './login.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component LoginComponent.


Error: libs/users/src/lib/pages/login/login.component.html:28:56 - error TS4111: Property 'required' comes from an index signature, so it must be accessed with ['required'].

28                 <span *ngIf="loginForm.password.errors.required">Password is required.</span>
                                                          ~~~~~~~~

  libs/users/src/lib/pages/login/login.component.ts:11:18
    11     templateUrl: './login.component.html',
                        ~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component LoginComponent.


Error: libs/users/src/lib/pages/login/login.component.ts:16:5 - error TS2564: Property 'loginFormGroup' has no initializer and is not definitely assigned in the constructor.

16     loginFormGroup: FormGroup;
       ~~~~~~~~~~~~~~


Error: libs/users/src/lib/pages/login/login.component.ts:37:35 - error TS4111: Property 'email' comes from an index signature, so it must be accessed with ['email'].

37             email: this.loginForm.email.value,
                                     ~~~~~


Error: libs/users/src/lib/pages/login/login.component.ts:38:38 - error TS4111: Property 'password' comes from an index signature, so it must be accessed with ['password'].

38             password: this.loginForm.password.value
                                        ~~~~~~~~


Error: libs/users/src/lib/services/auth-guard.service.ts:22:27 - error TS7006: Parameter 'expiration' implicitly has an 'any' type.

22     private _tokenExpired(expiration): boolean {
                             ~~~~~~~~~~


Error: libs/users/src/lib/services/localstorage.service.ts:11:14 - error TS7006: Parameter 'data' implicitly has an 'any' type.

11     setToken(data) {
                ~~~~


Error: libs/users/src/lib/services/localstorage.service.ts:15:9 - error TS2322: Type 'string | null' is not assignable to type 'string'.
  Type 'null' is not assignable to type 'string'.

15         return localStorage.getItem(TOKEN);
           ~~~~~~




✖ Failed to compile.

Dodam tylko, że do aplikacji w tym samym nx (admin) wstrzykuję również moduł, w którym znajduje się ten serwis (libs/orders/src/lib/orders.module.ts) i tam nie ma takich problemów.

Jak tylko usunę w komponencie import:

import { CartService } from '@webappshop/orders';

oraz:

 constructor(private cartService: CartService) {}

Błędy znikają i aplikacja renderuje się poprawnie.

Bardzo proszę o pomoc.

0

Chodzi za pewne o to, że localStorage.getItem(CART_KEY) zwraca typ string|null, a JSON.parse() przyjmuje string, więc jest to niekompatybilność typów.

Powinieneś obsłużyć to, dodając if i w jakiś sposób zareagować na przypadek kiedy localStorage.getItem() zwróci null (np rzucić wyjątek lub pokazać informację użytkownikowi, albo po prostu zignorować to). Innym wyjściem, jeśli jesteś absolutnie pewien że getItem() nigdy nie zwróci null, to możesz rzutować typ string|null na string używając !. Takie rzutowanie to po prostu zaniechanie silnego typowania, na rzecz dynamicznego (czyli trochę niweluje sens używania TypeScripta).

0

Tak, właśnie wiem, poprawiam wszystko. Problem polega na tym, że nie wiem czemu tak się stało. Wcześniej miałem też mode strict i nie krzyczało mi takich błędów. Wszystko prawidłowo się kompilowało i renderowano, natomiast od razu po imporcie tej biblioteki mam tych błędów ponad 40, np (zawsze tak pisałem):

    private _getCartItems() {
        const cart: Cart = this.cartService.getCart();
        if (cart) {
            this.orderItems = cart.items.map((item) => {
                return <OrderItem>{
                    product: item.productId,
                    quantity: item.quantity
                };
            });
        }
    }

Błąd:

Error: libs/orders/src/lib/pages/checkout-page/checkout-page.component.ts:58:31 - error TS18048: 'cart.items' is possibly 'undefined'.

58             this.orderItems = cart.items.map((item) => {

oczywiście wyżej mam:

orderItems: OrderItem[] = [];

oraz model

export class OrderItem {
    product?: string;
    quantity?: number;
}

Ale przecież tu sprawdzam czy jest undefined czy nie (co robię nie tak?):

if (cart)

EDIT
tutaj zrobiłem tak:

private _getCartItems() {
        const cart: Cart = this.cartService.getCart();
        if (cart && cart.items) {
            this.orderItems = cart.items.map((item) => {
                return <OrderItem>{
                    product: item.productId,
                    quantity: item.quantity
                };
            });
        }
    }

Natomiast chodzi mi o samą ideę - że po dodaniu biblioteki takie błędy dostałem (jak ją usunę aplikacja działa prawidłowo(kompiluje się i renderuje))

1 użytkowników online, w tym zalogowanych: 0, gości: 1