Iterate through an array of objects Angular 2 component - javascript

Can anyone help what I am doing incorrect, anything missing?
I am getting undefined for --'this.ack.length'
this._activeChannelService.requestChannelChange(this.selectedchannel.channelName)
.subscribe(
ack => {
this.ack= ack;
console.log(" test: ", this.ack.length);
},
err => {
console.log(err);
});enter code here
ack is of time
ack:Iack[];
Iack has two field of type string. result and message
I need to iterate through array of Iack[] to get the result and message
if message=success then call the another service
service
requestChannelChange (name: string): Observable<Iack[]> {
alert('in servicerequestChannelChange');
let headers = new Headers({'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
let postchannelname = "channelName=" + name;
let requestt = new IRequest(name);
console.log(JSON.stringify(requestt));
return this._http.post(this._activateChangeUrl, JSON.stringify(requestt),{ headers: headers })
//.map(this.extractData)
.map((res:Response) => res.json() as Iack[])
.do(data => console.log("All: " + JSON.stringify(data)))
.catch(this.handleError);
}

You can use observable in your TS service:
import { Injectable } from '#angular/core';
import { IPost } from './IPost';
import { Http, Response, RequestOptions, Headers } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
#Injectable()
export class PostServices {
private _webApiBaseUrl = "http://localhost:62806/v1/Posts"
private _http : Http;
constructor(http : Http){
this._http = http;
}
getAll(): Observable<IPost[]> {
        return this._http.get(this._webApiBaseUrl + '/all', this.getHeaders())
.map((response: Response) => response.json())
.do(data => console.log(`All Data: \n ${ JSON.stringify(data) }`))
.catch(this.handleError);
    }
private handleError(error: Response){
console.error(error);
return Observable.throw(error.json().error || 'Server Error');
}
private getHeaders()
{
let headers = new Headers();
headers.append("Authorization", "");
headers.append("Content-Type", "application/json");
return new RequestOptions({ headers: headers });
}
}
Usage in your TS class:
import { Component, OnInit } from '#angular/core';
import { IPost } from './IPost';
import { PostServices } from './posts.service';
#Component({
selector: 'app-posts',
templateUrl: './posts.component.html',
styleUrls: ['./posts.component.css']
})
export class PostsComponent implements OnInit {
posts: IPost[];
errorMessage: string;
private _postService: PostServices;
constructor(postService: PostServices) {
this._postService = postService;
}
ngOnInit() {
this._postService.getAll()
.subscribe(
data => {this.posts = data; console.log("data.length: " + data.length)}, // here
error => this.errorMessage = <any>error
);
}
}

enter code here is executed before this.ack= ack; is executed
This is a function
ack => {
this.ack= ack;
console.log(" test: ", this.ack.length);
}
that you pass to subscribe(...) and the observable calls it when the data arrives which can take a looong time when it's a call to a server.
enter code here is executed immediately.

You'll have to check for success within the service subscription. An observable is an asynchronous call, so any calls you want to make regarding the data in that async call must be made within it to remain a safe call.
So, make your seconds service call, within the subscription.

Related

Angular 9: Uncaught DOMException: Blocked a frame with origin

I just developed sign in authentication for an Angular app and I went to test it. Sign up works just fine. Then I sign out and attempt to sign in and the header does not update as expected, instead I get this error in console:
Uncaught DOMException: Blocked a frame with origin
"chrome-extension://hdokiejnpimakedhajhdlcegeplioahd" from accessing a
cross-origin frame.
at e [as constructor] (chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/lpfulllib.js:1:1441712)
at new e (chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/lpfulllib.js:1:1444920)
at chrome-extension://hdokiejnpimakedhajhdlcegeplioahd/lpfulllib.js:1:1461728
But I am not authenticated because I get:
{authenticated: false, username: null}
authenticated: false
username: null
Even though the GET request itself went through successfully, but there is a problem there, because it's not supposed to be a GET but a POST request. Why does it think it's a GET request?
My signin() method inside my auth service clearly shows it's a post request:
signin(credentials: SigninCredentials) {
return this.http.post(this.rootUrl + "/auth/signin", credentials).pipe(
tap(() => {
this.signedin$.next(true);
})
);
}
Here is my auth http interceptor code:
import { Injectable } from "#angular/core";
import {
HttpEvent,
HttpInterceptor,
HttpHandler,
HttpRequest,
HttpEventType,
} from "#angular/common/http";
import { Observable } from "rxjs";
#Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
// Modify or log the outgoing request
const modifiedReq = req.clone({
withCredentials: true,
});
return next.handle(modifiedReq);
}
}
Now I do not think the issue is in my AuthHttpInterceptor, I believe the problem is in AuthService:
import { Injectable } from "#angular/core";
import { HttpClient } from "#angular/common/http";
import { BehaviorSubject } from "rxjs";
import { tap } from "rxjs/operators";
interface UsernameAvailableResponse {
available: boolean;
}
interface SignupCredentials {
username: string;
password: string;
passwordConfirmation: string;
}
interface SignupResponse {
username: string;
}
interface SignedinResponse {
authenticated: boolean;
username: string;
}
interface SigninCredentials {
username: string;
password: string;
}
#Injectable({
providedIn: "root",
})
export class AuthService {
rootUrl = "https://api.my-email.com";
signedin$ = new BehaviorSubject(false);
constructor(private http: HttpClient) {}
usernameAvailable(username: string) {
return this.http.post<UsernameAvailableResponse>(
this.rootUrl + "/auth/username",
{
username,
}
);
}
signup(credentials: SignupCredentials) {
return this.http
.post<SignupResponse>(this.rootUrl + "/auth/signup", credentials)
.pipe(
tap(() => {
this.signedin$.next(true);
})
);
}
checkAuth() {
return this.http
.get<SignedinResponse>(this.rootUrl + "/auth/signedin")
.pipe(
tap(({ authenticated }) => {
this.signedin$.next(authenticated);
})
);
}
signout() {
return this.http.post(this.rootUrl + "/auth/signout", {}).pipe(
tap(() => {
this.signedin$.next(false);
})
);
}
signin(credentials: SigninCredentials) {
return this.http.post(this.rootUrl + "/auth/signin", credentials).pipe(
tap(() => {
this.signedin$.next(true);
})
);
}
}
I see you have no HttpHeaders. While I do not see your backend configuration, I suspect the mis configuration causes your exception.
You can update your Angular interpector to something like this:
import {
HttpEvent,
HttpHandler,
HttpHeaders,
HttpInterceptor,
HttpRequest,
} from '#angular/common/http'
import { Injectable } from '#angular/core'
import { Observable } from 'rxjs'
#Injectable()
export class AuthHttpInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
// const token = localStorage.getItem('access_token')
// const userToken = localStorage.getItem('id_token')
if (token) {
const authRequest = req.clone({
setHeaders: {
'Content-Type': 'application/json',
// Authorization: `Bearer ${token}`,
// userID: `${userToken}`,
},
})
return next.handle(authRequest)
} else {
const headers = new HttpHeaders({
'Content-Type': 'application/json',
})
const cloned = req.clone({
headers,
})
return next.handle(cloned)
}
}
}
Also make sure that your backend is aligned and headers such as Access-Control-Allow-Origin configured to true
That is caused by LastPass extension. Deactivate it and the error will disappear.

How can I take the data in this service from an HTTP get call?

I have a little issue from an Angular app to get a code from my own server.
I´ve built up a little Spotify App for learning more about Angular 10 and have a little backend that I only use for get the Bearer code to call the Spotify API, but the fact is that in my Angular front I can´t save the code.
Tis is my service call code to the back:
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { map } from 'rxjs/operators';
import { environment } from '../../environments/environment';
#Injectable({
providedIn: 'root'
})
export class SpotifyService {
token: any;
constructor(private http: HttpClient) {
console.log('Spotify service ready');
this.getAccesToken().subscribe(data => this.token = data['access_token']);
}
getAccesToken(){
return this.http.get(environment.server + `${environment.client_id}/${environment.client_secret}`)
.pipe(
map(res => res)
);
}
getQuery(query: any){
const headers = new HttpHeaders({
'Authorization': `Bearer ${this.token}`
});
const url = `https://api.spotify.com/v1/${query}`;
return this.http.get(url, {headers});
}
I´ve checked the recibed data and I get the request perfectly, but can´t save the data of the suscriber into a variable.
Thanks in advance!
Assuming your component code looks like below, you can make some adjustments and try it.
export class SomeComponent implements OnInit {
spotifyData;
user;
token;
constructor(private spotifyService: SpotifyService, private http: HttpClient) { }
ngOnInit() {
this.user = JSON.parse(localStorage.getItem('user'));
console.log(this.user);
this.token = this.user.token;
this.getSpotifyData();
}
getSpotifyData() {
this.spotifyService.getQuery(this.user, { headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.token) }).subscribe(res => {
console.log(res);
if (res) {
spotifyData = res;
} else {
spotifyData = []
}
});
}

trying to create a dynamic ng2 search.service

I'm trying to create a dynamic ng2 search.service. REST services are the underlying protocol for searching for data in my org. Here's a user.service that I originally created which searches for users:
import { Injectable } from '#angular/core';
import { Headers, Http, Response } from '#angular/http';
import 'rxjs/add/operator/toPromise';
import { User } from '../entities/user';
#Injectable()
export class UserService {
private headers = new Headers({ 'Content-Type': 'application/json' });
private usersUrl = 'http://localhost:4000/users';
private userUrl = 'http://localhost:4000/users/#id';
constructor(private http: Http) { }
getUser(id: number): Promise<User> {
return this.http.get('http://localhost:4000/users/1')
//return this.http.get(this.userUrl.replace('#id', id))
.toPromise()
//.then(this.extractData)
.then(response => response.json())
.catch(this.handleError);
}
getUsers(): Promise<User[]> {
return this.http.get(this.usersUrl)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
private extractData(response: Response) {
return response.json();
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
Here's my first attempts at a generic search.service:
import { Injectable } from '#angular/core';
import { Headers, Http, Response } from '#angular/http';
import 'rxjs/add/operator/toPromise';
import { User } from '../entities/user';
#Injectable()
export class SearchService
{
private _headers = new Headers({ 'Content-Type': 'application/json' });
private _entityName = '';
private _allEntitiesUrl = 'http://localhost:4000/#entityNames';
private _entityByIdUrl = 'http://localhost:4000/#entityNames/#id';
constructor(private http: Http, entityName: string)
{
this._allEntitiesUrl = entityName + 's';
this._entityByIdUrl = entityName + 's';
}
getEntity(id: number): Promise<User>
{
var url = this._entityByIdUrl.replace('#id', id.toString());
return this.http.get(url)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
getEntities(): Promise<User[]>
{
return this.http.get(this._allEntitiesUrl)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
private extractData(response: Response)
{
return response.json();
}
private handleError(error: any): Promise<any>
{
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
The search.service is only partially complete right now. Here are some things that I know need to be updated:
The import statement needs to be made generic or somehow accomodate the different types of entities that could potentially be returned from the search.service. For example, the search.service could potentially return accounts, products, etc:
import { User } from '../entities/user';
I need to figure out how to implement dynamic return types for getEntity/getEntities. I've done some work to implement methods to return generic types from C# in the past but not sure how this would be done with ng2/typescript
I'm sure I'm not the first person who has thought about doing this so hopefully others here who are more fluent in ng2/typescript can explain how I could implement this?
The import statement needs to be made generic or somehow accomodate the different types of entities that could potentially be returned from the search.service. For example, the search.service could potentially return accounts, products, etc:
In TypeScript you can create an interface and then have the different items implement that interface. Your search service can then return the type of you interface. e.g.
class User implements Entity
and the service would then be
getEntities(): Promise<Entity[]>
{
return this.http.get(this._allEntitiesUrl)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
I need to figure out how to implement dynamic return types for getEntity/getEntities. I've done some work to implement methods to return generic types from C# in the past but not sure how this would be done with ng2/typescript
The other option is as you mention here is to use generics e.g.
getEntities<T>(): Promise<T[]>
{
return this.http.get(this._allEntitiesUrl)
.toPromise()
.then(response => response.json())
.catch(this.handleError);
}
which would be called as
getEntities<User>()

Type Promise<void> is not assignable to type Promise<customType[]>

I am new to angularJs2. I have created following service:
import { Injectable, OnInit } from '#angular/core';
import { customType } from '../models/currentJobs';
import { Headers, Http } from '#angular/http';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class JobService implements OnInit {
constructor(private http: Http) { }
ngOnInit(): void {
this.getCurrentJobs();
}
private headers: Headers = new Headers({ 'Content-Type': 'application/json' });
private ordersUrl: string = 'http://localhost:35032/api/order/';
public orders: customType[];
getCurrentJobs(): Promise<customType[]> {
var jobs = this.http.get(this.ordersUrl)
.toPromise()
.then(response => {
this.orders = response.json() as customType[];
})
.catch(this.handleError);
return jobs;//this line throws error
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}
Following are my Typescript compile configuration of Vs2017
When I compile the code using visual studio 2017 I get following error
**TS2322 Build:Type 'Promise<void>' is not assignable to type 'Promise<customType[]>'.**
Help me to fix this error.
You are not returning anything inside your then which makes jobs be of type Promise<void>. Return the array inside then:
getCurrentJobs(): Promise<customType[]> {
var jobs = this.http.get(this.ordersUrl)
.toPromise()
.then(response => {
this.orders = response.json() as customType[];
return this.orders;
})
.catch(this.handleError);
return jobs;
}
See the chaining behaviour of promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then#Chaining
I've added the 'catch' operator, and swapped your interface import for an interface definition in the code (as I don't obviously have access to yours). I can't really test this without the rest of your project code, but it looks right to me and doesn't throw any errors in VSC.
import { Injectable, OnInit } from '#angular/core';
import { Headers, Http } from '#angular/http';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/catch';
export interface customType{
}
#Injectable()
export class JobService implements OnInit {
constructor(private http: Http) { }
private jobs: Promise<customType[]>;
ngOnInit(): void {
this.jobs = this.getCurrentJobs();
}
private headers: Headers = new Headers({ 'Content-Type': 'application/json' });
private ordersUrl: string = 'http://localhost:35032/api/order/';
public orders: customType[];
getCurrentJobs(): Promise<customType[]> {
return this.http.get(this.ordersUrl)
.map(response => response.json())
.catch(this.handleError)
.toPromise();
}
private handleError(error: any): Promise<any> {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
}

Angular2 post request not sending proper data to server

I am taking the field of a form and passing it to a service as this.form.value when I am logging this.form.value on the console I am getting Object { email: "zxzx", password: "zxzxx" } when I am sending the same thing to the service and calling the server like :
import {Http} from 'angular2/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';
import {Injectable} from 'angular2/core'
import {Post} from './post';
import {Observable} from 'rxjs/Observable';
#Injectable()
export class PostService {
//dependency injection
private _url = "http://127.0.0.1/accounts/login_user/";
constructor(private _http:Http) {
}
createPost(post){
return this._http.post(this._url,JSON.stringify(post))
.map(res=>res.json());
}
}
The server is being called but the values are not being passed. When I am logging the response on the console I am getting :
Object { _isScalar: false, source: Object, operator: Object }
Can somebody please help me solve this issue?
Thank you.
Your console.log prints the observable corresponding to your request but not its result. If you want to print this result, you can use the do operator:
createPost(post){
return this._http.post(this._url,JSON.stringify(post))
.map(res=>res.json())
.do(data => {
console.log(data);
});
}
You said that the request is executed. It's actually the case if you subscribe on the observable:
this.service.createPost(...).subscribe(() => {
(...)
});
Edit
You also need to set the Content-Type header:
createPost(post){
var headers = new Headers();
headers.append('Content-Type', 'application/json');
return this._http.post(this._url,JSON.stringify(post), { headers })
.map(res=>res.json())
.do(data => {
console.log(data);
});
}
Edit2
If you want to send an url-encoded form:
You also need to set the Content-Type header:
createPost(post){
var headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let content = new URLSearchParams();
content.set('prop', post.prop);
(...)
return this._http.post(this._url, content.toString(), { headers })
.map(res=>res.json())
.do(data => {
console.log(data);
});
}
You need to subscribe() otherwise the observable won't do anything:
createPost(post){
return this._http.post(this._url,JSON.stringify(post))
.map(res=>res.json())
.do(val => console.log(val));
}
...
this.createPost(...).subscribe(data => console.log(data));

Categories