Showing posts with label Angular. Show all posts
Showing posts with label Angular. Show all posts

Call chatgpt api from angular

Angular is a frontend framework that allows you to build web applications, and you can use it to make HTTP requests to external APIs, including the ChatGPT API. 

To call the ChatGPT API from Angular, you would typically use Angular's built-in HttpClient module to send HTTP requests to the API endpoint. Here's a basic example of how you might do this: 

First, make sure you have Angular CLI installed. If not, you can install it using npm:

npm install -g @angular/cli

Create a new Angular project:

ng new my-chatgpt-app

Navigate to your project directory:
cd my-chatgpt-app

Generate a new service to handle API calls:
ng generate service chatgpt

In your service file (chatgpt.service.ts), import HttpClient and inject it into your service constructor:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

  providedIn: 'root'
export class ChatGptService {
  private apiUrl = ''; // Example API endpoint

  constructor(private http: HttpClient) { }

  getChatResponse(prompt: string): Observable<any> {
    const headers = {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer YOUR_API_KEY' // Replace YOUR_API_KEY with your actual API key

    const body = {
      prompt: prompt,
      max_tokens: 150

    return<any>(this.apiUrl, body, { headers });

Replace '' with the actual URL of the ChatGPT API endpoint you want to call.
Replace 'YOUR_API_KEY' with your actual ChatGPT API key.
Now, you can use this service in your Angular components to make API calls. For example, in your component file (app.component.ts), you can inject the ChatGptService and call the getChatResponse method:
import { Component } from '@angular/core';
import { ChatGptService } from './chatgpt.service';

  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
export class AppComponent {
  constructor(private chatGptService: ChatGptService) {}

  ngOnInit() {
    this.chatGptService.getChatResponse('Hello, GPT!').subscribe(response => {

Here we are printing data to the console, you can print it in an HTML page as well.


Angular’s new output() API in Angular v17.3 with practical example | output() API in Angular v17.3

 In Angular, components often need to communicate with their parent components by emitting events or data. The traditional way to achieve this has been using the @Output decorator with EventEmitter. While it works, the new output() API (introduced in Angular version 17.3 as a developer preview) offers several advantages:

  • Simpler and Safer: It provides a more concise and less error-prone way to declare outputs.
  • Type Safety: It enforces stricter type checking, preventing potential runtime errors due to incorrect data types being emitted.
  • Consistency: It aligns with other function-based APIs like input() and model() in Angular, making your code more consistent and easier to understand

Limitation to using a traditional approach to declaring outputs or @output

The traditional approach to declaring outputs in Angular components using @Output and EventEmitter had some limitations that the new output() and outputFromObservable() APIs aim to address:

1. More Boilerplate Code:

  • The old approach required manual instantiation of an EventEmitter for each output:

@Output() someEvent =newEventEmitter();

  • This could lead to more verbose code, especially for components with multiple outputs.

2. Potential Type Safety Issues:

  • With EventEmitter, you had to manually ensure that the emitted data matched the desired type.
  • This could lead to runtime errors if you accidentally emit the wrong data type.

3. Less Consistent Style:

  • The use of EventEmitter didn't align with other function-based Angular APIs like @Input() and [(ngModel)].
  • This could make code less readable and maintainable.

How output() and outputFromObservable() address these limitations:

  • Concise Syntax: Both new APIs offer a more concise way to declare outputs, removing the need for manual EventEmitter creation.

         // New approach
2  someEvent = output();
4// Old approach
5@Output() someEvent =new EventEmitter();

  • Improved Type Safety: These APIs enforce stricter type checking, ensuring emitted values match the declared type. This helps prevent runtime errors.

  • Consistent Style: They align with other function-based APIs, making the code more consistent and easier to understand.

In summary, the new output() and outputFromObservable() APIs offer a more streamlined, type-safe, and consistent approach to declaring outputs in Angular components compared to the traditional @Output and EventEmitter.

Angular’s new output() API in 

Angular v17.3 with a practical example 


Angular v17.2 is now available | Angular v17.2 is released

 Angular v17.2 is now available and released on Feb 14, 2024. 

While Angular v17.2 is considered a minor release, it still packs some interesting surprises and improvements:

Key Features:

  • Experimental Material 3 Support
 Get a glimpse of the future with basic usage of Material 3 components like MatButton, MatCard, and MatIcon. Material 3 is basically an alternative theme and still material 2 will be in support.
below is the Saas code

@use '@angular/material' as mat; @use '@angular/material-experimental' as matx; .dark-theme { @include mat.all-component-themes($m3-dark-theme); } .light-theme { @include mat.all-component-themes($m3-light-theme); }

and below is the component code

// app.component.ts import { Component } from '@angular/core'; @Component({ selector: 'app-root', template: ` -card class="light-theme"> Welcome to Angular!</h2> -button class="dark-theme">Click me</mat-button> </mat-card> `,
}) }
  • Signal Queries
  • A signal is basically a wrapper around a value that can notify users whenever the value changes. 
  • Signals can contain any type of value, from simple primitives to complex data structures. 
  • A signal value is always read-only using the getter function, which allows us to track where the signal is used.
@viewChild, @viewchildern decorators, and  ngAfterViewInit() life cycle hook are now signal based alternatives

 // app.component.ts

// app.component.ts import { Component } from '@angular/core'; @Component({ template: ` element to signal query</div> ` }) export class App { // it returns the Signal | undefined> divEle = viewChild>('ele'); // it returns the Signal> and it ensures that signal value is not undefined divEleReq = viewChild.required>('ele'); // it returns Signal[]> divEles = viewChildren('ele'); }

and now ngAfterViewInit is replaced by the signal Effect, so now no need for the ngAfterViewInit lifecycle hook, this signal effect will be used in the constructor

import {Component,effect} from '@angular/core' ; import {RouterOutlet} from '@angular/router' ; @Component({ selector:'app-root' , standalone : true , imports : [RouterOutlet ], templateUrl : './app.component.html' , styleUrl : './app.component.css' }) export class AppComponent { constructor () { effect (() => { console.log("output"); }) } }
Model Inputs:
 Now we have signal signal-based alternative to ngModel, Simplify template syntax for binding values to DOM inputs like checkboxes and radio buttons.

it introduces the model (this is the new regular API) which we can directly use i template and it will help us in the way data binding

import { Component, effect } from '@angular/core'; import { RouterOutlet } from '@angular/router'; @Component({ selector: 'app-root', standalone: true, imports: [RouterOutlet], //templateUrl: './app.component.html', styleUrl: './app.component.css', template: ` ="checkbox" [(checked)]="isChecked"> Is checked? `, }) export class AppComponent { isChecked : boolean = false; protected checked = model(false); //this is the new regular API }

    • Netlify Loader: Integrate Angular applications seamlessly with Netlify's deployment platform.

     // angular.json (architect -> build -> options)

    "outputHashing": "all", "sourceMap": true, "budgets": [ { "type": "initial", "maximumWarning": "250kb", "maximumError": "300kb" } ], "ngswConfigPath": "angular.json.ngsw", "serviceWorker": true, "optimization": true, "scripts": [ // ... "node_modules/@angular/platform-server/dist/esm/platform-server.mjs" ], "styles": [ // ... ], "loader": { "type": "netlify" }

        • Hydration Debugging in DevTools
         Identify and resolve data mismatches between server-rendered and client-hydrated content. you can enable it in the Angular DevTools settings and use it to inspect data discrepancies between server-rendered and client-hydrated components.

        Other Enhancements:

        • Control Vite development server pre-bundling for more granular optimization.
        • Configure PostCSS directly within the application builder for tailored styling.
        • Various bug fixes and stability improvements across the core framework. 
        • Angular CLI now supports Bun's package manager for a different build experience.


        • These features are mainly experimental and might change in future releases.
        • Consider upgrading to v17.2 for a taste of the future and explore the experimental functionalities.