Tag Archives: Angular

Ng Zorro antd file stream upload, access to upload file path

HTML page

<nz-upload 
        nzAccept="application/pdf,image/jpeg,image/jpg,image/png"
        [(nzFileList)]="fileList"
        [(nzAction)]="UPLOAD_FILE"
        [nzShowButton]="fileList.length < 1"
        [nzBeforeUpload]="beforeUpload"
        (nzChange)="getFileUrl($event)" >
        <button nz-button>
            <i nz-icon nzType="upload"></i>
            <span>upload files</span>            
        </button>
</nz-upload>

TS file

 import { Component, OnInit } from '@angular/core';
 import { NzMessageService, NzModalService, UploadFile } from 'ng-zorro-antd';
    
 @Component({
     selector: 'app-detail',
     templateUrl: './detail.component.html',
     styleUrls: ['./detail.component.scss']
 })
 export class DetailComponent implements OnInit {
  	UPLOAD_FILE = ''; // File upload path
    constructor(
         private activeRoute: ActivatedRoute,
         private msg: NzMessageService,
         private router: Router,
         private message: NzModalService,
    ){ }
              
    fileList: UploadFile[] = [];
  	beforeUpload = (file: UploadFile): boolean => {
         // Judgment on the upload file type
         const type = file.type;
               
         const str = ['application/pdf', 'image/jpg', 'image/jpeg', 'image/png'];
              if (str.indexOf(type) < 0) {
                  this.message.warning({
                      nzTitle: 'Warning',
                      nzContent: 'Select file failed, only pdf, jpg, jpeg, png and other formats are supported'
                  });
                  return false;
              }
              // Limit on upload file size
              const isLt20M = file.size / 1024 / 1024 < 30;
              if (!isLt20M) {
                  this.message.warning({
                      nzTitle: 'Warning',
                      nzContent: 'The file must be less than 30M'
                  });
                  return false;
              }
              this.fileList = this.fileList.concat(file);
              // When the type and size meet the requirements, upload directly; if return false, then you need to call the upload method manually
              return true;
          }
          // Method to get the path when the file upload is finished     	 
      getFileUrl({ file, fileList }): void {
              const status = file.status;
              if (status === 'done') {
                this.zizhi_prove = file.response.data
              } else if (status === 'error') {
                this.msg.error(`${file.name} file upload failed.`);
              }
        }
  	}

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

  Time: May 8, 2021 14:22:35

ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.. Find more at https://angular.io/errors/NG0100
    at throwErrorIfNoChangesMode (core.js:6792)
    at bindingUpdated (core.js:12940)
    at Module.ɵɵproperty (core.js:14740)
    at InvoiceManagementComponent_Template (invoice-management.component.html:55)
    at executeTemplate (core.js:9600)
    at refreshView (core.js:9466)
    at refreshComponent (core.js:10637)
    at refreshChildComponents (core.js:9263)
    at refreshView (core.js:9516)
    at refreshEmbeddedViews (core.js:10591)

The meaning of the problem is that once the page is rendered, don’t change it. If you change it again, I will report you an error. And that’s it.

Solution: add a line of code to the ngafterviewinit() method

  ngAfterViewInit(): void {
    this.changeDetectorRef.detectChanges();
  }

This only needs to be declared in the constructor

  constructor(
    public changeDetectorRef: ChangeDetectorRef
  ) { }

 

The difference between problem and observables

There is a discussion on stackoverflow: what is the difference between problems and observables?

A useful blog: angular2 observables, HTTP, and separating services and components

An article on the official website of angular: observables compared to other technologies

The difference between observable and promise:

Observables are declarative; computation does not start until subscription. Promises execute immediately on creation. This makes observables useful for defining recipes that can be run whenever you need the result.

Observable is declarative, and calculation is not triggered until subscription. This is very different from promise — promise is executed immediately after it is created.

Observables provide many values. Promises provide one. This makes observables useful for getting multiple values over time.

Observable provides multiple values, while promises can only provide a single value.

Observables differentiate between chaining and subscription. Promises only have .then() clauses. This makes observables useful for creating complex transformation recipes to be used by other part of the system, without causing the work to be executed.

Observable can be combined into complex transformation recipes with the help of rich operators in rxjs, which is convenient for reuse in application, while promise has only one then operation.

Observables subscribe() is responsible for handling errors. Promises push errors to the child promises. This makes observables useful for centralized and predictable error handling.

Property ‘style’ does not exist on type ‘element‘

Property ‘style’ does not exist on type ‘element’ property does not exist on type ‘element’
Reason: This is caused by TypeScript type checking, which requires a type assertion in front of the querySelector method.

let frameContainObj = document.getElementById("model_view_container")
let iframeObj= <HTMLElement>frameContainObj.querySelector("#modelView");
iframeObj.style.height = document.documentElement.clientHeight* 0.65 + "px";

Extensions: When using QuerySelectorAll, the following scenario can be used:

let block = document.querySelectorAll(".block") as NodeListOf<HTMLElement>;

Tells the TypeScript compiler to pass this code by setting assertions

Ngif of module in ionic 5 + angular

Use ionic5 pop-up box with the following code:

const modal = await this.modalController.create({
      component: MyComponent,
      componentProps: {
        title: option.title || '',
      },
      cssClass: 'my-custom-class'
    });
    await modal.present();
    const { data } = await modal.onDidDismiss();
    return data;

Then there is an ngIf directive in MyComponent, run the error:

Can't bind to 'ngIf' since it isn't a known property

The reason:
Angular routes are not loaded into MyComponent’s Module
Solutions:
1. Import the module of MyComponent in app.module.ts
2. Import the module where the MyComponent resides in the module.ts of the page that uses the pop-up box

ionic Uncaught (in promise): Error: StaticInjectorError[NavController]

Error: Uncaught (in promise): Error: StaticInjectorError[NavController]
By default you can’t use navController or viewController or anything like that in a Controller or a service.
Code:


An easier solution,

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { NavController, AlertController, App } from 'ionic-angular';
import {LoginPage} from "../pages/login/login";
@Injectable()
export class CommonProvider {

    public session:any;
    constructor(
        public http: HttpClient, 
        public alertCtrl: AlertController, 
        public appCtrl : App
    ) {}

    public getSession() {
        let activeNav: NavController = this.appCtrl.getActiveNav();
        this.session = window.localStorage.getItem('session');
        if(!this.session) {
            activeNav.setRoot(LoginPage);
            return false;
        }
        return this.session;
    }

Reference: https://www.cnblogs.com/wupeng88/p/8340947.html

Solve angular’s cannot find module ‘@ angular devkit / core’ problem

after angular creation program, to add new components, but sometimes there will be “Cannot find module ‘@angular-devkit/core'” problem, the reason for this problem is the lack of @angular-devkit/core. In fact, this problem will prompt
at the time of new program creation, such as ng new newProject will appear after execution

npm WARN @angular-devkit/schematics@0.0.52 requires a peer of @angular-devkit/core@0.0.29 but none is installed. You must install peer dependencies yourself.
npm WARN @schematics/angular@0.1.17 requires a peer of @angular-devkit/core@0.0.29 but none is installed. You must install peer dependencies yourself.

in these tips are @ presents – devkit/core is not installed successfully, the need to install the prompt
solution is installed, enter the directory executing the following command

npm i --save-dev @angular-devkit/core

if again prompted @angular-devkit/core did not install successfully you need to uninstall angular-cli and reinstall angular-cli

npm uninstall -g angular-cli
npm install -g @angular/cli@latest

will solve

after reinstallation

Angular: Program ng failed to run No application is associated

today, when building the Angular CLI framework, I encountered a strange problem. When I finished Angular CLI setup, I typed the ng command on Windows PowerShell and command prompt, which worked fine, but failed on VSCode PowerShell.

I’ve sorted out the solutions here, hoping to be of some help to those reading this article.

problem description

The following error occurred when I typed the ng command on VSCode PowerShell.

Program 'ng' failed to run: No application is associated with the specified file for this operationAt line:1 char:1

ng
~~.
At line:1 char:1
ng
~~
CategoryInfo : ResourceUnavailable: (:) [], ApplicationFailedException
FullyQualifiedErrorId : NativeCommandFailed

solution

change PowerShell execution policy on a Windows machine. Here are the steps:

get the list of execution policies

enter the following command to get a list of PowerShell execution policies:

Get-ExecutionPolicy -List

set CurrentUser policy

set CurrentUser to the remoteswignet strategy and enter the command ‘

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser


after the above steps are completed, close the VSCode PowerShell, and then restart it. Finally, re-enter the ng command to check if it was successful.

  • if errors still occur, you can try to close all existing command prompt and PowerShell Windows.

  • try to restart your computer if you still have problems.

  • if the problem still exists, please check whether the C:\Users\{username}\AppData\ NPM environment variable is set.

  • finally, you can also try reinstalling Angular CLI.

try it all over again anyway to make sure it works.