Visual Studio can't find toPromise - visual-studio

i used Visual Studio for a WebApp-Projekt with Angular2 as frontend and asp.core as backend.
Now i want to get a status from my API. The Api works, i used it first with postman.
In my Angular-Component, the component says it does not know about toPromise(). i think the code works, but visual studio blocked to build the app.
import { Injectable } from '#angular/core';
import { ImportState } from './importstate';
import { Headers, Http } from '#angular/http';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class ImportService {
private headers = new Headers({ 'Content-Type': 'application/json', 'user': 'Superadmin', 'password':'Rest!12345' });
private heroesUrl = 'api/import/'; // URL to web api
constructor(private http: Http) { }
getStatus(type : string): Promise<ImportState> {
return this.http.get(this.heroesUrl + 'getStatus/' + type, { headers: this.headers })
.toPromise()
.then(response => response.json() as ImportState)
.then(r => console.log(r))
.catch(this.handleError);
}
private handleError(error: any): Promise<any> {
//console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
}
I hope somebody can help me.

Related

Angular, error 500 after sending the request in the header

I have a hard time passing the right angular request to the header. This is my service:
import { Injectable } from '#angular/core';
import { HttpClient, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpHeaders }
from '#angular/common/http';
import { Utente } from '../model/Utente ';
import { Prodotto } from '../model/Prodotto ';
import { OktaAuthService } from '#okta/okta-angular';
import { Observable, from } from 'rxjs';
import { Carrello } from '../model/Carrello ';
import { userInfo } from 'node:os';
import { getLocaleCurrencyCode } from '#angular/common';
const headers = new HttpHeaders().set('Accept', 'application/json');
#Injectable({
providedIn: 'root'
})
export class HttpClientService {
constructor(
private httpClient:HttpClient, private oktaAuth:OktaAuthService ) {}
getCarr(){
return this.httpClient.get<Carrello[]>('http://localhost:8080/prodotti/utente/vedicarrelloo', {headers} );
}
}
This is my spring method:
#Transactional(readOnly = true)
public List<Carrello> getCarrello(#AuthenticationPrincipal OidcUser utente){
Utente u= utenteRepository.findByEmail(utente.getEmail());
return carrelloRepository.findByUtente(u);
}
In console I get this error (error 500):
https://i.stack.imgur.com/BiONS.png
this error corresponds in my console to "java.lang.NullPointerException: null.
But if I access localhost: 8080, I can see the answer correctly, so I assume there is a problem in passing the request header in angular, can anyone tell me where am I wrong, please? I specify that I get this error only in the methods where the OidcUser is present, the rest works perfectly. Thank you!
You need to send an access token with your request. Like this:
import { Component, OnInit } from '#angular/core';
import { OktaAuthService } from '#okta/okta-angular';
import { HttpClient } from '#angular/common/http';
import sampleConfig from '../app.config';
interface Message {
date: string;
text: string;
}
#Component({
selector: 'app-messages',
templateUrl: './messages.component.html',
styleUrls: ['./messages.component.css']
})
export class MessagesComponent implements OnInit {
failed: Boolean;
messages: Array<Message> [];
constructor(public oktaAuth: OktaAuthService, private http: HttpClient) {
this.messages = [];
}
async ngOnInit() {
const accessToken = await this.oktaAuth.getAccessToken();
this.http.get(sampleConfig.resourceServer.messagesUrl, {
headers: {
Authorization: 'Bearer ' + accessToken,
}
}).subscribe((data: any) => {
let index = 1;
const messages = data.messages.map((message) => {
const date = new Date(message.date);
const day = date.toLocaleDateString();
const time = date.toLocaleTimeString();
return {
date: `${day} ${time}`,
text: message.text,
index: index++
};
});
[].push.apply(this.messages, messages);
}, (err) => {
console.error(err);
this.failed = true;
});
}
}
On the Spring side, if you want it to accept a JWT, you'll need to change to use Jwt instead of OidcUser. Example here.
#GetMapping("/")
public String index(#AuthenticationPrincipal Jwt jwt) {
return String.format("Hello, %s!", jwt.getSubject());
}

Angular UI not updating after data changes

Im new to the MEAN stack and having trouble with getting data changes to be refreshed in the UI. I know the data is getting saved properly in MongoDB, and also retrieved, because when I create a Todo item and I refresh the page, the newly added Todo item appears in the Todo List. The problem is that it isnt happening dynamically.
I've tried a number of different things including NgZone and ChangeDetectorRef to detect changes, not sure what I'm doing wrong..
Let me know if any more info is needed.. thank you!
The Todo List component:
import { Component, Input, OnInit, NgZone } from '#angular/core';
import { Todo } from '../todo.model';
import { TodoService } from '../../todo.service';
#Component({
selector: 'app-todo-list',
templateUrl: './todo-list.component.html',
styleUrls: ['./todo-list.component.scss'],
providers: [TodoService]
})
export class TodoListComponent implements OnInit {
#Input() todos: Todo[] = [];
constructor(private _todoService: TodoService, private zone: NgZone){}
getTodos() {
console.log('todo list - get todos');
this._todoService.getTodos()
.subscribe(resTodoData => {
this.zone.run(() => {
this.todos = resTodoData;
});
});
}
ngOnInit() {
console.log('todo list - init');
this.getTodos();
}
}
Service Component:
import { Injectable, NgZone } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from
'#angular/http';
import { map } from 'rxjs/operators';
import { Todo } from './todos/todo.model';
#Injectable({
providedIn: 'root'
})
export class TodoService {
// these were configured in express server
private _getUrl = "/api/todos";
private _postUrl = "/api/todo";
constructor(private _http: Http, private zone: NgZone) { }
getTodos() {
let json = this._http.get(this._getUrl)
.pipe(map((response: Response) => response.json()));
return json;
}
addTodo(todo: Todo) {
let headers = new Headers({ 'Content-Type': 'application/json'
});
let options = new RequestOptions({ headers: headers });
return this._http.post(this._postUrl, JSON.stringify(todo),
options)
.pipe(map((response: Response) => response.json()));
}
}

Why XMLHttpRequest works but Angular2+ returns a 404?

I'm using angular6.
When getHello gets called it returns a 404 error.
import { Injectable } from '#angular/core';
import { HttpClient, HttpHeaders } from '#angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
#Injectable({ providedIn: 'root' })
export class RequisicaoTransporteService {
constructor(private http: HttpClient) { }
getHello() : Observable<any> {
return this.http.post('http://localhost:17844/api/requisicaotransporte/getHello',{},httpOptions)
};
}
This is how i call it:
this.requisicaoTransporteService.getHello()
.subscribe(x => this.hello = x);
When i do the following, it works fine:
$.ajax({
type: "POST",
url: "http://localhost:17844/api/requisicaotransporte/gethello",
success:function(o){console.log(o);}
});
The server allows CORS.

Parse Image from Microsoft Graph API

After i looked up the www, stackoverflow and youtube, i couldn't find an concrete answer about, how to fetch an image correctly from:
https://graph.microsoft.com/beta/me/photo/$value
in TypeScript/JavaScript. The solution is really easier as i thought. You just need this an additional information in your GET Request:
responseType: ResponseContentType.ArrayBuffer
The complete solution looks like this:
import { DomSanitizer } from "#angular/platform-browser";
import { Http, Headers, ResponseContentType } from "#angular/http";
import "rxjs/add/operator/map";
import { AlertController } from "ionic-angular";
export class GraphService {
constructor(
private http: Http,
private alertCtrl: AlertController,
private sanitizer: DomSanitizer
) {}
transform(html) {
return this.sanitizer.bypassSecurityTrustUrl(html);
}
getProfileImage(accessToken: string) {
// fetch User Profile Image
let headers: Headers = new Headers();
headers.append("Authorization", "Bearer " + accessToken);
this.http
.get("https://graph.microsoft.com/beta/me/photo/$value", {
responseType: ResponseContentType.ArrayBuffer,
headers: headers
})
.map(res => res)
.subscribe(
(data: any) => {
let blob = new Blob([data.arrayBuffer()], {
type: data.headers.get("content-type")
});
let imageUrl = window.URL.createObjectURL(blob);
return this.transform(imageUrl));
},
error => {
let alert = this.alertCtrl.create({
title: "GraphProvider",
subTitle: "Can't fetch profile image!",
buttons: ["OK"]
});
alert.present();
}
);
}
}
The most important part is: don't append the responseType: ResponseContentType.ArrayBuffer in your header! You have to provide it beside the header! And don't forget to import it from #angular/http!
I hope I could help all the lost souls out there :D
PS: Thanks to Micheal Mainer for the Graph Explorer Repo: https://github.com/microsoftgraph/microsoft-graph-explorer/tree/e2a376615d14c5eabd51e972478b18827800d323
here's my fetched Image from Microsoft Graph API:

The specified content type was not found - Error 611 - NativeScript

I'm following the step by step tutorial of NativeScript but I'm facing the following issue:
When I try to make a post request through my Angular service I get the following error:
JS: {"message":"The specified content type was not found.","errorCode":611}
My code looks pretty much the same as the one in the official docs from NativeScript:
import { Injectable } from '#angular/core';
import { Http, Headers, Response } from '#angular/http';
import { User } from './user';
import { Config } from '../config';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/map';
#Injectable()
export class UserService {
constructor(private _http: Http) { }
register(user: User): Observable<Response> {
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const url = `${Config.apiUrl}/Users`;
const body = JSON.stringify({
Username: user.email,
Email: user.email,
Password: user.password
});
return this._http.post(url, body, { headers })
.catch(this.handleErrors);
}
handleErrors(error: Response) {
console.error(JSON.stringify(error.json()));
return Observable.throw(error);
}
}
Component class:
signUp() {
this._user.register(this.user).subscribe(
() => {
alert('Your account has been successfully created.');
this.toggleDisplay();
},
() => {
// errors here...
alert('Unfortunately we were unable to create your account.');
}
);
}
Tested under Android and IOs, both throws the same error.
Isn't application/json the expected Content-Type in this case?
If I change the type I get another error saying that the type is missing or is invalid.
Can someone please point out what am I missing?

Resources