Variable not found in .suscbribe

Can someone help me understand why it's saying that "post" is not defined on line 20 in my home.component.ts file? Here is the code below. Any input would be appreciated, thank you!

home.component.ts

import { Component, OnInit } from '@angular/core';
import { Post } from '../_models/index';
import { PostService } from '../_services/index';
@Component({
    moduleId: module.id,
    templateUrl: 'home.component.html'
})
export class HomeComponent implements OnInit {
    posts: Post[] = [];

    constructor(private postService: PostService) { }

    ngOnInit() {
        // get posts from secure api end point
        this.postService.getPosts().subscribe(users => {
            this.posts = post;
        });
    }
}

post.ts

import { Injectable } from '@angular/core';
import {Author} from "./author";

@Injectable()
export class Post {
    id:number;
    author:Author;
    subscribed:boolean;
    created:string;
    active:boolean;
    text:string;
    comments:string[];

    constructor(id:number, author:Author, subscribed:boolean, created:string, active:boolean, text:string, comments:string[]) {
        this.id = id;
        this.author = author;
        this.subscribed = subscribed;
        this.created = created;
        this.active = active;
        this.text = text;
        this.comments = comments;
    }

    public static getPosts():Post{
        return new Post(0, null, null, "", null, "",null);
    }
}

post.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/add/operator/map';

import { AuthenticationService } from './index';
import { Post } from '../_models/index';

@Injectable()
export class PostService {
    constructor( private http: Http, private authenticationService: AuthenticationService) {}

    getPosts(): Observable<Post[]> {
        // add authorization header with jwt token
        let headers = new Headers();
        headers.append('Authorization','token ' + this.authenticationService.token);

          headers.append('Content-Type', 'application/json');
          let options = new RequestOptions({
              headers: headers
          });  //  console.log(headers);

        // get posts from api
        return this.http.get('http://localhost:8000/areas/fun/', options)
        .map((response: Response) => response.json());
    }
}

If you need more information, feel free to ask. Thanks!

Answer №1

Since the variable post was not declared, you encountered an issue.

It appears that you were attempting to achieve something like this:

import { Component, OnInit } from '@angular/core';
import { Post } from '../_models/index';
import { PostService } from '../_services/index';

@Component({
    moduleId: module.id,
    templateUrl: 'home.component.html'
})
export class HomeComponent implements OnInit {
    posts: Post[] = [];

constructor(private postService: PostService) { }

ngOnInit() {
    // obtain posts from secure api endpoint
    this.postService.getPosts()
        .subscribe(post => {
            this.posts = post;
        });
    }
}

The issue stemmed from: .subscribe(user => { being corrected to .subscribe(post => {

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The element ion-virtual-scroll is unrecognized

<ion-virtual-scroll [items]="churchNewsList" approxItemHeight="120px"> <ion-item *virtualItem="let news"> {{ news }} </ion-item> </ion-virtual-scroll> I encountered an issue with the following error messag ...

Bypass URL Routing for a specific route in Angular 8 and Apache

I currently have two Angular applications: the FrontEnd and Admin. Both of these are hosted on cPanel behind an Apache server. The website setup is as follows: mydomain.com/ ----> Frontend Angular Application mydomain.com/admin ----> Admin Angular ...

Using the js-cookie library in a TypeScript-based project: A guide

Looking to incorporate the js-cookie library into my TypeScript project. After installing the library and typings with the command npm install js-cookie @types/js-cookie --save-dev in the location containing node_modules and package.json, my package.json ...

Tips for Incorporating Material Design Lite into Angular2

I have encountered a minor issue while trying to incorporate material design into Angular2. I am using the latest version of Angular2, but the MDL framework seems to be incompatible. Here is what I have done so far: npm install material-design-lite --sav ...

Deleting a key from a type in TypeScript using subtraction type

I am looking to create a type in TypeScript called ExcludeCart<T>, which essentially removes a specified key (in this case, cart) from the given type T. For example, if we have ExcludeCart<{foo: number, bar: string, cart: number}>, it should re ...

The installed NPM package does not contain the necessary TypeScript compiled JS files and declaration files

I have recently released a TypeScript library on NPM. The GitHub repository's dist (Link to Repository Folder) directory includes all compiled JavaScript and d.ts files. However, after running npm i <my_package>, the resulting module contains on ...

Getting the value of a specific key in angularfire2 - a simple guide

The task at hand involves retrieving a specific value labeled as UID from the database structure below. this.af.database.object('/profile/' + this.uid).subscribe(profile => { console.log(profile); this.uid = profile.uid; console.log(th ...

What is the best way to retrieve paginated data from a simulated JSON server (json-server)?

Looking to return a page using JSON server found at https://github.com/typicode/json-server. The current JSON structure appears as follows: records :[ { id: '2', name: 'k', }, { id:'3', name:'j' } ] Successfully abl ...

Exploring the functionalities of React with TypeScript using the useState hook

I'm currently attempting to retrieve my project data from Firebase and store it in an array using hooks. Each project has a structure similar to: {name: "movie app", date: t, description: "this is my first app, a complete movie app"} //hooks const [p ...

Positioning the box at the exact middle of the screen

I'm trying to center an item on the screen using material ui, but it's appearing at the top instead of the middle. How can I fix this? import * as React from 'react'; import Box, { BoxProps } from '@mui/material/Box'; functio ...

Dependencies of generic types among function arguments

Exploring the implementation of binding in a game engine, I aim to incorporate a touch of typing. /** Engine external functions */ export type Message<TBody> = { } // This function returns the same unique object for the same `s` // An internal engi ...

Using Angular Ionic 3 to apply the disabled attribute

I have a situation in my main.ts where I need to disable a textarea in the HTML if an object is initialized. I've attempted various methods like: ng-attr-disabled="!myObj"; ng-attr-disabled="{myObj!= null}"; and also directly using ng-disabled. I e ...

Apollo is unable to upload the file within the class Object

I am currently working on a project where I need to upload files using a multipart request in Graphql. However, I have encountered an issue when creating an object of a class that contains a File - the file is not being uploaded. Strangely enough, if it is ...

When trying to display an image from Firebase, the request went to http://localhost:4200/undefined

https://i.sstatic.net/EqNpy.pngWhen attempting to display an image stored in Firebase, I encountered an error stating GET http://localhost:4200/undefined 404 (Not Found). I attempted to resolve this issue by adding the condition *ngIf="albumImages.userIma ...

Implementing personalized validation post-control initialization in an Angular 4 reactive form

I have been working on an Angular 4 application and using reactive forms. For one of my forms, I am trying to implement custom validation on a control after it has been initialized, based on whether a checkbox is checked or unchecked. CODE form.componen ...

Library types for TypeScript declaration merging

Is there a way to "extend" interfaces through declaration merging that were originally declared in a TypeScript library file? Specifically, I am trying to extend the HTMLCanvasElement interface from the built-in TypeScript library lib.dom. While I underst ...

TypeScript versions 2.3 and 2.4 experiencing issues with generic overloads

After upgrading from typescript 2.2, I encountered an issue with the following example. interface ILayoutResult { id: string; data: any; } interface ILayout{ getResult<T extends ILayoutResult | ILayoutResult[] | void>() :T; } class te ...

Guide to retrieving Response Header in Angular 8 when making a POST request

Looking to fetch the response Header in Angular 8 after a post request and securely store the jwt token in localstorage? login(req): Observable<any> { return this.http.post(this.apiUrl + '/login', req).pipe( map(res => { if ...

Instructions on how to access a JSON file in an angular-cli npm test by importing it

With Angular version 4.2.4 and angular-cli at version 1.1.3, the code snippet below is used: import languagesJsonRaw from './languages/en.json'; import countriesJsonRaw from './countries/en.json'; export const languages = prepareLangu ...

Determining the Best Option: React JS vs Angular UI Framework

After researching the latest versions of React and Angular online, I discovered that both are suitable for developing Web Application UI. However, I also realized that there are key differences to consider when choosing between the two. Let's say I h ...