Reputation: 15092
Found some answers for angularjs like: How to use angular.toJson on a angular controller or scope but not Angular 2 and following.
I'm new to Angular, worked through the tutorial, and now trying to build my first live app. I have a credentials object that has fields username and password. I want to externalize this to JSON to send to my web service. I found this: https://angular.io/api/common/JsonPipe which seems to do what I want, but the example is in HTML and I want to do it in my service, so here's my service:
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { JsonPipe } from '@angular/common';
import { Observable } from 'rxjs/Observable';
import { of } from 'rxjs/observable/of';
@Injectable()
export class LoginService {
authToken = ""
loginUrl = "localhost:8093/login"
constructor(private http: HttpClient) { }
login(credentials): Observable<String> {
var url = this.loginUrl
+ '?payload='
+ (credentials | json)
return of(url);
}
}
But I get an error on the line + (credentials | json)
saying json is not found, maybe I meant JSON?
Did I?
Upvotes: 2
Views: 5949
Reputation: 658037
Just use
JSON.stringify(credentials)
like in plain JavaScript.
The | json
pipe is only for view binding like
{{credentials | json}}
but not for TypeScript code.
Upvotes: 5