Introduces some Angular development problems and solutions

1. Process multiple HTTP requests simultaneously

Service scenario: A web page contains multiple independent drop-down lists, and the drop-down lists need to be loaded simultaneously.

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/observable/merge';
import 'rxjs/add/observable/zip';

let http1 = this.http.get('url');
let http2 = this.http.get('url');
let http3 = this.http.get('url');

Observable.forkJoin(http1, http2, http3).subscribe((res) => {
      console.log(res)
    })

Observable.zip(http1, http2, http3).subscribe(([res1, res2, res3]) => {
      console.log(res1)
      console.log(res2)
      console.log(res3)
    })

Observable.zip(http1, http2, http3).subscribe((res) => {
      console.log(res)
    })

Observable.merge(http1, http2, http3).subscribe((res) => {
      console.log(res)
    })Copy the code

2. Return Observable in the Promise

Business scenario: This problem occurred during Ionic development. At that time, I was making a demo and required the API address to be configured on the interface. The API address was stored in the APP cache through the Storage, and the CLIENT first obtained the API address from the cache when sending HTTP requests

import {Observable} from 'rxjs'; import 'rxjs/add/observable/fromPromise'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/mergeMap'; post(url, parametersModel): Observable<any> { //this.storage.get(...) Return a Promise, this.http.post(...) Get ('apiBaseUrl')). MergeMap (apiBaseUrl => {return this.http.post(apiBaseUrl + url, parametersModel, { headers: this.headerWithToken() }); }); }Copy the code

3. Cannot read property ‘XXX’ of null

[Bad]

var data = null;
if (data.name) { // TypeError: Cannot read property 'name' of null
    console.log('OK');
}Copy the code

[Good]

var data = null;
if (data && data.name) {
    console.log('OK');
}Copy the code

4. Handle multiple promises at once

getStorage(names: Array<string>): Promise<Array<string>> { return Promise.all([this.storage.get(names[0]), this.storage.get(names[1])]); // this.storage.get returns Promise}Copy the code

5. Array deduplication

You can do this with es6’s new Set, which is a data structure that is very similar to an array but has unique values for its members. We can convert it to Set first and then cooperate with… The deconstruction operator is converted back into an array to achieve the purpose of de-duplication.

const arr = [1, 1, 2, 2, 3, 4, 5, 5]; const new_arr = [...new Set(arr)]; console.log(new_arr); // Output [1, 2, 3, 4, 5]Copy the code

6. Variable scope enhancement

Variable scope promotion, that is, a variable declared by var, gets to the top level of the variable. The variable is declared, not assigned, so it is printed as undefined. Let does not have variable scope enhancement

console.log(str); Var STR = '123456';Copy the code

[equivalent to]

var str; // STR is undefined console.log(STR); // undefined STR = '123456';Copy the code

7. Ajax operations implemented with Promise objects

const getJSON = function(url) { const promise = new Promise(function(resolve, reject){ const handler = function() { if (this.readyState ! == 4) { return; } if (this.status === 200) { resolve(this.response); } else { reject(new Error(this.statusText)); }}; const client = new XMLHttpRequest(); client.open("GET", url); client.onreadystatechange = handler; client.responseType = "json"; client.setRequestHeader("Accept", "application/json"); client.send(); }); return promise; }; getJSON("/posts.json").then(function(json) { console.log('Contents: ' + json); }, function(error) {console.error(' error ', error); });Copy the code

8. Empty and intercept the array by changing the array length

const arr = ['A','B','C','D','E','F']; arr.length = 3; console.log(arr); //=> ['A','B','C'] arr.length = 0; console.log(arr); / / = > []Copy the code

9. Create pure objects

const pureObject = Object.create(null); console.log(pureObject); / / = > {}Copy the code

10. Chain calls

The method of the class finally returns this

    class Person {
        constructor(name, age, tall) {
            this.name = name;
            this.age = age;
            this.tall = tall;
        }

        setName(name) {
            this.name = name;
            return this;
        }

        setAge(age) {
            this.age = age;
            return this;
        }

        setTall(tall) {
            this.tall = tall;
            return this;
        }

        save() {
            console.log(this.name, this.age, this.tall);
            return this;
        }
    }

    const myself = new Person();
    console.log(myself);
    myself.setAge(20).setName('Jack').setTall(3).save();Copy the code

11.DIV is evenly divided vertically

.father{ display:flex; flex-direction: column; div{ flex:1; }}Copy the code

12. Array sorted by a field

arr.sort((a,b)=>{
	return b.LayoutPosition - a.LayoutPosition
});
Copy the code

13. Slider control

function scrollToBottom() {
        console.log(document.getElementById('content').scrollHeight);
        const height = document.getElementById('content').scrollHeight;
        document.getElementById('content').scrollTo(0, height);
    }
Copy the code

14. Judge the value of 0

const flag = 0; console.log(flag === true); // false console.log(flag || flag === 0); // trueCopy the code