I have an component where i am adding a new object called customer by calling the api like this:
public onAdd(): void {
this.myCustomer = this.customerForm.value;
this.myService.addCustomer(this.myCustome).subscribe(
() => { // If POST is success
this.callSuccessMethod();
},
(error) => { // If POST is failed
this.callFailureMethod();
},
);
}
Service file:
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable, Subject } from 'rxjs';
import {ICustomer } from 'src/app/models/app.models';
#Injectable({
providedIn: 'root',
})
export class MyService {
private baseUrl : string = '....URL....';
constructor(private http: HttpClient) {}
public addCustomer(customer: ICustomer): Observable<object> {
const apiUrl: string = `${this.baseUrl}/customers`;
return this.http.post(apiUrl, customer);
}
}
As shown in component code, i have already subscribed the api call like this:
this.myService.addCustomer(this.myCustome).subscribe(
() => { // If POST is success
.....
},
(error) => { // If POST is failed
...
},
);
But,I want to subscribe the results in another component, I have tried like this:
public getAddedCustomer() {
this.myService.addCustomer().subscribe(
(data:ICustomer) => {
this.addedCustomer.id = data.id; <======
}
);
}
I am getting this lint error: Expected 1 arguments, but got 0 since i am not passing any parameter.
What is the right approach to subscribe the api call in other components? after POST operation.
Because i want to get added object id for other functionality.
Well it totally depends on the design of your application and the relation between components. You can use Subjects for multicasting the data to multiple subscribers.
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable, Subject } from 'rxjs';
import { ICustomer } from 'src/app/models/app.models';
#Injectable({
providedIn: 'root',
})
export class MyService {
private baseUrl : string = '....URL....';
private latestAddedCustomer = new Subject();
public latestAddedCustomer$ = this.latestAddedCustomer.asObservable()
constructor(private http: HttpClient) {}
public addCustomer(customer: ICustomer): Observable<object> {
const apiUrl: string = `${this.baseUrl}/customers`;
return this.http.post(apiUrl, customer).pipe(map((data) => this.latestAddedCustomer.next(data)));
}
}
and subscribing to the subject as follows
this.latestAddedCustomer$.subscribe()
should get you the latest added customer details. Even though i would not do this the way its written. I would basically write a seperate service to share the data between the components or would write a cache service if its used across the application. But the idea here is to use the concept of Subjects. You can read more about it Here
Related
So I'm making a simple notes app using Entity Framework with ASP.Net Core for my backend and AngularJS for frontend.
The expected behaviour is that when the app initiates, it should load a list of notes that are already saved in my database (MySQL)
Thing is, when my app does the Get request it rertuns the following error:
Before this I had a problem with CORS that I solved by adding http:// to my connection string and after solving that, I got this. I've been looking all over the internet but I don't seem to find an answer.
This is my note.service.ts
import { HttpClient } from '#angular/common/http';
import { Injectable } from '#angular/core';
import { Observable } from 'rxjs';
import { Note } from '../note';
#Injectable({
providedIn: 'root'
})
export class NoteService {
private url: string = "http://localhost:44353/api/NotesLists";
constructor(private http: HttpClient) { }
getNotes(): Observable<Note[]> {
return this.http.get<Note[]>(this.url);
}
}
This is my home component (where I subscrirbe to get the response):
import { Component, OnInit } from '#angular/core';
import { NoteService } from '../services/note.service';
import { Note } from '../note';
#Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {
public notes: Note[] = [];
constructor(private noteService: NoteService) { }
ngOnInit(): void {
this.noteService.getNotes()
.subscribe(data => this.notes = data);
}
}
And my [HttpGet] request on .Net Core
[HttpGet]
public IActionResult Get()
{
try
{
var response = _datacontext.NotesList
.Include(notesList => notesList.Note)
.ToList();
if (response.Count == 0)
{
return NotFound();
}
return Ok(response);
}
catch (Exception e)
{
return StatusCode(500, e.Message);
}
}
And my DataContext for better context (Ha!)
using Microsoft.EntityFrameworkCore;
using noteAppAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace noteAppAPI.Helpers
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> option) : base(option)
{
}
public DbSet<NotesList> NotesList { get; set; }
public DbSet<Note> Notes { get; set; }
}
}
Thanks to #MarkHomer for his suggestion in the comments. The solution to this was:
Change connection string on note.service.ts from
private url: string = "http://localhost:44353/api/NotesLists";
to
private url: string = "http://localhost:44353/api/NotesLists";
This would lead me to have to enable CORS in my API so the HTTPS request would work.
To enable CORS in Startup.cs add in ConfigureServices method:
services.AddCors(c =>
{
c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
});
services.AddDbContext<DataContext>(option => {
option.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});
And also in Configure method in the same file:
app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
I am following a tutorial on which we create an Angular service for sending emails from
a form using Mailthis Email API.
In the service code I get an error on the 'api' word that says
" Property 'api' does not exist on type 'MyService' ".
Any advice will be very helpfull!
My code is:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { map } from 'rxjs/operators';
#Injectable({
providedIn: 'root'
})
export class MyService {
constructor(private http:HttpClient
) { }
PostMessage(input:any){
return this.http.post(this.api, input, { responseType:'text' }).pipe(
map(
(response:any) => {
if(response){
return response;
}
},
(error:any) => {
return error;
}
)
)
}
}
I don't see anywhere you have defined api as a variable, i assume it is the endpoint you want to call, so you can define it as
api: string = "yourUrl";
I have a DataServive, that fetches content from an API:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { map, catchError, retry } from 'rxjs/operators';
import { environment } from 'src/environments/environment';
#Injectable()
export class DataService {
this.request = {
count: 10
}
constructor(private http: HttpClient) { }
private handleError(error) {
console.log(error);
}
public getData(count): Observable<any> {
this.request.count = count;
return this.http.post<any>(environment.api + '/path', this.request).pipe(
map(response => {
return response;
}),
catchError(error => {
this.handleError(error);
return [];
})
);
}
}
This DataServie is consumned by a component like this:
ngOnInit() {
const subscriber = this.dataService.getData(this.count).subscribe((data) => { this.data = data; });
}
And it works fine.
However the user is able to change the variable this.count (how many items should be displayed) in the component. So I want to get new data from the server as soon as this value changes.
How can I achieve this?
Of course I could call destroy on this.subscriber and call ngOnInit() again, but that dosn't seem like the right way.
Easiest ways is just to unsubscribe:
subscriber: Subscription;
ngOnInit() {
this.makeSubscription(this.count);
}
makeSubscription(count) {
this.subscriber = this.dataService.getData(this.count).subscribe((data) => { this.data = data; });
}
functionInvokedWhenCountChanges(newCount) {
this.subscriber.unsubscribe();
makeSubscription(newCount);
}
But because count argument is just a one number it means HTTP always asks for data from 0 to x. In this case, you can better create another subject where you can store previous results (so you don't need to make useless HTTP requests) and use that subject as your data source. That needs some planning on your streams, but is definitely the preferred way.
When the user changes count, call getData(count) again with the updated count value. Need to see your html file, but having a button with (click)="getData(count)" may help.
I have a question about the Angular 5 httpClient.
This is a model class with a method foo() I'd like to receive from the server
export class MyClass implements Deserializable{
id: number;
title: string;
deserialize(input: any) {
Object.assign(this, input);
return this;
}
foo(): string {
// return "some string conversion" with this.title
}
}
This is my service requesting it:
import { Injectable } from '#angular/core';
import { HttpClient } from '#angular/common/http';
import { Observable } from 'rxjs';
import { MyClass } from './MyClass';
#Injectable({
providedIn: 'root',
})
export class MyClassService {
constructor(private http: HttpClient) {
}
getMyStuff(): Observable<MyClass[]> {
// this is where I hope to convert the json to instances of MyClass
return this.http.get<MyClass[]>('api/stuff')
}
}
My Problem
When I ask the service for instances of MyClass I get the data, but I cannot run {{ item.foo() }} in the template. Also, when I console.log() the typeof of an item where it is received in the service, I do no see instances of an object of MyClass.
What am I doing wrong? I thought that writing this.http.get<MyClass[]>('api/stuff') would do the conversion.
Any hints? Thank you in advance!
When doing that, TypeScript only does "type assertion". It means that you're telling TypeScript that your object is of type MyClass, but the object isn't actually an instance of MyClass at runtime. In order to call functions defined in your model object, you have to define constructors in your model classes like that :
constructor(obj?: any) {
Object.assign(this, obj);
}
Then in your services add a mapping like this :
http.get<MyClass>('/my-class').pipe(
map(res => new MyClass(res))
Note: the code above is RxJS 6 style, i don't know which version you are using
It works for me like this
import { HttpClient } from '#angular/common/http';
...
this.httpClient.get<MyResponse>('http://......').toPromise()
.then((myResponse) => {
console.log('myResponse.myField: ' + JSON.stringify(tokenResponse));
})
.catch((error) => {
console.log('Promise rejected with ' + JSON.stringify(error));
});
...
interface MyResponse {
myField: string;
myOtherField: string;
}
I'm new to Angular and TypeScript and just started working on a project using MEAN stack (MongoDB, Express, Angular, Node.js).
I created this mongoose module :
import * as mongoose from 'mongoose';
var Schema = mongoose.Schema;
const entrepriseSchema = new mongoose.Schema({
name: {type: String, unique: true, required : true},
telephone: Number,
logo: String,
web_site: String,
sites: [
{site_id: {type: Schema.Types.ObjectId, ref: 'Site'}}
]
});
const Entreprise = mongoose.model('Entreprise', entrepriseSchema);
export default Entreprise;
and this is my entreprise.component.ts :
import { Component, OnInit } from '#angular/core';
import { Http } from '#angular/http';
import { FormGroup, FormControl, Validators, FormBuilder } from '#angular/forms';
import { ActivatedRoute } from '#angular/router';
import { EntrepriseService } from '../services/entreprise.service';
import { SiteService } from '../services/site.service';
#Component({
selector: 'app-entreprise',
templateUrl: './entreprise.component.html',
styleUrls: ['./entreprise.component.scss'],
providers: [EntrepriseService, SiteService]
})
export class EntrepriseComponent implements OnInit {
entreprise = {};
sites = [];
id: String;
constructor(private entrepriseService: EntrepriseService,
private siteService: SiteService,
private http: Http,
private route: ActivatedRoute) {
this.id = route.snapshot.params['id'];
}
ngOnInit() {
this.getEntrepriseById(this.id);
//not working
//console.log(this.entreprise.name);
//console.log(this.entreprise.sites);
//this.getSitesIn(this.entreprise.sites);
}
getEntrepriseById(id) {
this.entrepriseService.getEntreprise(id).subscribe(
data => this.entreprise = data,
error => console.log(error)
);
}
getSitesIn(ids) {
this.siteService.getSitesIn(ids).subscribe(
data => this.sites = data,
error => console.log(error)
);
}
}
when I try to display the properties of the returned from entreprise.component.html it works fine and displays all the properties :
<h3>{{entreprise.name}}</h3>
<div *ngFor="let site of entreprise.sites">
{{site.site_id}}
</div>
{{entreprise.logo}}
{{entreprise.web_site}}
but how can I access the same properties on the TypeScript side ?
The commented code in the EntrepriseComponent is what I'm trying to accomplish but it's not working since this.entreprise is type {} .
The Enterprise model/schema that you created in Mongoose in Node.js resides on the server side. If you want the TypeScript code on the UI to recognize the properties in Enterprise, you will have to create a class in your angular codebase.
Create a folder named, say, models at the same level as your services folder. (Optional)
Create two files named site.ts and enterprise.ts in the models folder created in the previous step (You can put these file at a different location if you want) with the following contents:
site.ts
export interface Site {
site_id?: string;
}
enterprise.ts
import { Site } from './site';
export interface Enterprise {
name?: string;
telephone?: string;
logo?: string;
web_site?: string;
sites?: Site[];
}
Now, inside the EntrepriseComponent file, add the following imports
import { Enterprise} from '../models/entreprise';
import { Site } from '../models/site';
And change the first lines inside the EntrepriseComponent file to
export class EntrepriseComponent implements OnInit {
entreprise: Enterprise = {};
sites: Site[] = [];
Now, the enterprise attribute will be of type Enterprise and you will be able to access the properties that we declared in the enterprise.ts file.
Update:
Also, you cannot console.log(this.enterprise.name) immediately after this.getEntrepriseById(this.id); in your ngOnInit() function. This is because the web service you are making to get the enterprise object would not have resolved when you are trying to log it to the console.
If you want to see the enterprise object in the console or you want to run some code that needs to run after the service call has resolved and the this.enterprise object has a value, the best place to do this would be your getEntrepriseById function. Change the getEntrepriseById function to
getEntrepriseById(id) {
this.entrepriseService.getEntreprise(id).subscribe(
data => {
this.enterprise = data;
console.log(this.enterprise.name);
// Any code to run after this.enterprise resolves can go here.
},
error => console.log(error)
);
}