J. Doe J. Doe - 2 months ago 33
TypeScript Question

Add function in angular 2, how do i get a new id for a contact database?

I try to build up a Contactform, my Problem is that i can't get a new ID for the POST-Function. It always set me this emit:

{
_isScalar: false,
operator: Object {...},
source: Object {...}
}


What could i do to get the new ID, and i Need following ID´s like this: 1,2,3,...

public Add = (Name: string, Nachname: string, Geburtsdatum: string, Strasse: string, Hausnummer: string, Postleitzahl: string, Wohnort: string): Observable<boolean> => {
let id = this._http.get(this.actionUrl + 'getid', { headers: this.headers })
.map(res => res.json());

var toAdd = JSON.stringify({
Id: id,
Name: Name,
Nachname: Nachname,
Geburtsdatum: Geburtsdatum,
Strasse: Strasse,
Hausnummer: Hausnummer,
Postleitzahl: Postleitzahl,
Wohnort: Wohnort
});

console.error(toAdd);

var res = this._http.post(this.actionUrl, toAdd, { headers: this.headers })
.map(res => true)
.catch(this.handleError);

console.error(res);
return res;
}

Answer

The first problem I can spot is, that you're not subscribing to your http.get request there. If you're not adding the subscribe call, the request will never be executed.

Also: Observables are async by nature, so you don't get your value back from the call like you'd expect. You have to do so in the subscribe callback. That also means that every logic that depends on that response goes into that callback. You can however chain multiple on each other depending Observables with the .flatMap call.

public Add = (Name: string, Nachname: string, Geburtsdatum: string, Strasse: string, Hausnummer: string, Postleitzahl: string, Wohnort: string): Observable<boolean> => {
    return this._http.get(this.actionUrl + 'getid', { headers: this.headers })
        .map(res => res.json())
        .flatMap(res => {
            var toAdd = JSON.stringify({ 
                Id: res, // depends on what your getid call returns 
                Name: Name, 
                Nachname: Nachname, 
                Geburtsdatum: Geburtsdatum, 
                Strasse: Strasse, 
                Hausnummer: Hausnummer, 
                Postleitzahl: Postleitzahl, 
                Wohnort: Wohnort 
            });

            console.error(toAdd);

            return this._http.post(this.actionUrl, toAdd, { headers: this.headers })
                .map(res => {
                    console.log(res);
                    return true; // maybe return the actual result?
                 }) 
                .catch(this.handleError);
        }
    );
}

The res variable you're logging there is an Observable and not the actual result from your database. You can log the response inside the .map method, where you're returning true for some reason.

Comments