Angular app keeps saying message does not exist - django

I'm building a chat app with Angular and Django using the get stream tutorial. https://getstream.io/blog/realtime-chat-django-angular/
However, I'm trying to run the app to create the chat view but it keeps saying 'messages' does not exist at the point marked 'this point' in the code.
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
import { MessageResponse, Channel } from 'stream-chat';
import { StreamService } from '../stream.service';
import { StateService } from '../state.service';
declare const feather: any;
#Component({
selector: 'app-chat',
templateUrl: './chat.component.html',
styleUrls: ['./chat.component.scss'],
})
export class ChatComponent implements OnInit {
constructor(
public streamService: StreamService,
private stateService: StateService,
private router: Router
) {}
messages: MessageResponse[] = [];
message = '';
channel!: Channel;
async sendMessage() {
if (this.message) {
try {
await this.channel.sendMessage({
text: this.message,
});
this.message = '';
} catch (err) {
console.log(err);
}
}
}
getClasses(userId: string): { outgoing: boolean; incoming: boolean } {
const userIdMatches = userId === this.streamService.currentUser.messages.id; (this point)
return {
outgoing: userIdMatches,
incoming: !userIdMatches,
};
}
}

Related

401 "Unauthorized" error in Django and Angular File Upload

I have created a Django and Angular application to upload files. It was working without errors until I integrated a login page. I have not been able to upload files since integration. I get 401 - "Unauthorized" error. What could have possibly gone wrong?
Auth-interceptor:
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest,HttpErrorResponse } from "#angular/common/http";
import { Injectable } from "#angular/core";
import { catchError, Observable, throwError } from "rxjs";
import { LoginService } from "src/services/login.service";
#Injectable()
export class AuthInterceptorService implements HttpInterceptor {
constructor(private authService: LoginService) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.authService.isLoggedIn()) {
const token = this.authService.getAuthToken();
console.log("intercept",token)
// If we have a token, we set it to the header
request = request.clone({
setHeaders: {Authorization: `Token ${token}`}
});
}
return next.handle(request)
}
}
fileupload.component.ts:
import { Component, OnInit } from '#angular/core';
import { FormBuilder, FormGroup } from '#angular/forms';
import { LoginService } from 'src/services/login.service';
import { FileUploader, FileLikeObject } from 'ng2-file-upload';
import { concat, Observable } from 'rxjs';
import { HttpEvent, HttpEventType } from '#angular/common/http';
#Component({
selector: 'app-fileupload',
templateUrl: './fileupload.component.html',
styleUrls: ['./fileupload.component.scss']
})
export class FileuploadComponent {
DJANGO_SERVER = 'http://127.0.0.1:8081'
public uploader: FileUploader = new FileUploader({});
public hasBaseDropZoneOver: boolean = false;
constructor(private formBuilder: FormBuilder, private uploadService: LoginService) { }
fileOverBase(event): void {
this.hasBaseDropZoneOver = event;
}
getFiles(): FileLikeObject[] {
return this.uploader.queue.map((fileItem) => {
return fileItem.file;
});
}
upload() {
let files = this.getFiles();
console.log(files);
let requests= [];
files.forEach((file) => {
let formData = new FormData();
formData.append('file' , file.rawFile, file.name);
requests.push(this.uploadService.upload(formData));
console.log(requests,file)
});
concat(...requests).subscribe(
(res) => {
console.log(res);
},
}
);
}}
console.log(err);
}
);
}}
service:
public upload(formData) {
let token= localStorage.getItem('token');
return this.http.post<any>(`${this.DJANGO_SERVER}/upload/`, formData).pipe(map((res) => {
console.log(res)
})
)
}
Thank you
I resolved the issue. It was because I was usign interceptor and I was using third party API for authentication. So instead of Django token, the third party APIs token was sent in header of POST request.
How I resolved it?
I used Httpbackend to process POST requests to Django DB so that the request is not intercepted and then I added custom header (with Django token to the reuest). I used the code snippet on this website: https://levelup.gitconnected.com/the-correct-way-to-make-api-requests-in-an-angular-application-22a079fe8413

Ionic 2: Error testing with Karma/Jasmine/TestBed

I'm new with Ionic2 and I was following this tutorial and a simple test like
describe('Dummy test', () => {
it('should do nothing', () => {
expect(true).toBeTruthy();
expect(1 + 1).toBe(2);
});
});
works fine, but for some reason I keep getting this error when I try to follow the rest of the tutorial.
Component: Root Component
✖ initialises with a root page of LoginPage
Firefox 45.0.0 (Linux 0.0.0)
TypeError: win is undefined in src/test.ts (line 937)
My src/test.ts is the same as the tutorial and it doesn't have any win in it. My app.spec.ts is this
import { TestBed, ComponentFixture, async } from '#angular/core/testing';
import { IonicModule } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { UserData } from '../providers/user-data';
import { LoginPage } from '../pages/login/login';
import { Platform } from 'ionic-angular';
import { MyApp } from './app.component';
import { LoginPage } from '../pages/login/login';
let comp: MyApp;
let fixture: ComponentFixture<MyApp>;
describe('Component: Root Component', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [MyApp],
providers: [
StatusBar,
SplashScreen,
UserData,
Platform
],
imports: [
IonicModule.forRoot(MyApp)
]
}).compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(MyApp);
comp = fixture.componentInstance;
});
afterEach(() => {
fixture.destroy();
comp = null;
});
it('initialises with a root page of LoginPage', () => {
expect(comp['rootPage']).toBe(LoginPage);
});
});
And my app.component.ts is this
import { Component } from '#angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { MenuSidePage } from '../pages/menu-side/menu-side';
import { LoginPage } from '../pages/login/login';
import { UserData } from '../providers/user-data';
#Component({
template: `<ion-nav #nav [root]="rootPage"></ion-nav>`
})
export class MyApp {
rootPage: any;
constructor(
public platform: Platform,
public statusBar: StatusBar,
public splashScreen: SplashScreen,
private userData: UserData,
) {
platform
.ready()
.then(() => {
//First - check if user is logged
if(this.userData.currentUser) {
this.rootPage = MenuSidePage;
} else {
this.rootPage = LoginPage;
}
statusBar.styleDefault();
splashScreen.hide();
});
}
}
I don't have yet the solution, but you shouldn't use compileComponents() 'cause you are using a template and not a templateUrl like said in this tutorial :
"We need to use compileComponents when we need to asynchronously compile a component, such as one that has an external template (one that is loaded through templateUrl and isn’t inlined with template). This is why the beforeEach block that this code runs in uses an async parameter – it sets up an asynchronous test zone for the compileComponents to run inside."
Hope it's a kind of helping :)
The win() function come from the Plaftorm, you have to mock it as follow :
export class PlatformMock {
public ready(): Promise<string> {
return new Promise((resolve) => {
resolve('READY');
});
}
public getQueryParam() {
return true;
}
public registerBackButtonAction(fn: Function, priority?: number): Function {
return (() => true);
}
public hasFocus(ele: HTMLElement): boolean {
return true;
}
public doc(): HTMLDocument {
return document;
}
public is(): boolean {
return true;
}
public getElementComputedStyle(container: any): any {
return {
paddingLeft: '10',
paddingTop: '10',
paddingRight: '10',
paddingBottom: '10',
};
}
public onResize(callback: any) {
return callback;
}
public registerListener(ele: any, eventName: string, callback: any): Function {
return (() => true);
}
public win(): Window {
return window;
}
public raf(callback: any): number {
return 1;
}
public timeout(callback: any, timer: number): any {
return setTimeout(callback, timer);
}
public cancelTimeout(id: any) {
// do nothing
}
public getActiveElement(): any {
return document['activeElement'];
}
}
Here is the link to see a project for real integration of this mock class.
Hope it helps :)

Ionic 2: How to call Provider function in Controller class

I have created new Cordova Plugin only on my machine. Then I added it to my project. It is working fine when I call that plugin. Now, I tried to make a structured caller for my plugin. I created a Provider for it, but the problem is I don't know how to call my plugin function from my Controller class. Below is my sample code.
Provider: my-service.ts
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
declare let myPlugin: any;
#Injectable()
export class MyService {
constructor(public http: Http) {
console.log('Hello MyService Provider');
}
public myFunction() {
myPlugin.myPluginFunction(
(data) => {
return data;
},
(err) => {
return err;
});
}
}
Pages: my-page.ts
import { Component } from '#angular/core';
import { NavController, ViewController } from 'ionic-angular';
import { MyService } from '../../providers/my-service';
#Component({
selector: 'page-my-page-ionic',
templateUrl: 'hello-ionic.html'
})
export class MyPage {
constructor(private viewCtrl: ViewController, private myService: MyService) {}
ionViewWillEnter() {
//I tried to call like this
this.myService.myFunction().subscribe(
data => {
alert("success");
},
error => {
alert("error");
});
}
}
It returns me this error - Property 'subscribe' does not exist on type 'void'. I don't know how to call that function, since my provider returns me success or error.
I think since your myFunction() does not return any observable you cannot subscribe to it. It just returns data directly.
You can use it like this in this case:
var data = this.myService.myFunction();
console.log("Data from plugin is :", data);
If you want to use it as an Observable, return a new observable like this:
public myFunction() {
return Observable.create(observer => {
myPlugin.myPluginFunction(
(data) => {
observer.next(data);
},
(err) => {
observer.next(data);
});
},
(err) => {
observer.error(err);
});
}

How to write the post method in ionic?

I am new to the ionic framework,I had written the post call, I don't know exactly the post method.When i entered the submit button in forgot password page,if the user is already registered then should display the next page else it should display the alert message.
Below is my code:
import { Component } from '#angular/core';
import { configurator } from '../../providers/configurator';
import { NavController } from 'ionic-angular';
// import { LoginPage } from '../login/login';
import { persistence } from '../persistence/persistence';
#Component({
templateUrl: 'home.html'
})
export class home {
public loginId = "";
constructor(public navCtrl: NavController) {
}
generateOTP(newstate) {
console.log("invoking generateOTP FN");
var _this = this;
this.login.generateOTP(this.loginId, function(result,data){
if(result == '1') {
alert(data);
var a = document.createElement('a');
a.href="OTP page";
}
else {
//this.showRePasswd = this.showRePasswd;
alert(data);
}
})
}
}
This is my ionic-page:enter image description here
Can anyone help me!!!
my post belowed in IONIC2
import { Http, Response } from '#angular/http';
constructor(public navCtrl: NavController, private http: Http) { }
this.http.post(`${POST_URL}/log/add`, JSON.stringify(this.currentLocation), {headers})
.toPromise()
.then((response) => {
if (response.status !== 201) {
this.trace.error('log','postLog',`error response: ${response.status}`);
}
})
.catch(error => {
this.trace.error('log','postLog',`err post log:${error}`);
});

angular 2 RC4- Cannot resolve all parameters for 'Router'

I have written a test for my component and it is failing with
Error: Cannot resolve all parameters for 'Router'(?, ?, ?, ?, ?, ?,
?). Make sure that all the parameters are decorated with Inject or
have valid type annotations and that 'Router' is decorated with
Injectable.
import { Component, OnInit } from '#angular/core';
import { Router, ActivatedRoute } from '#angular/router';
import { Supplier } from './supplier';
import { SupplierService } from './supplier.service';
import { AppService } from '../shared/app.service';
#Component({
moduleId: module.id,
selector: 'supplier-form',
templateUrl: './supplier-form.component.html',
styleUrls: ['./supplier-form.component.css']
})
export class SupplierFormComponent implements OnInit {
private countries: any;
private model: Supplier;
private errorMessage: string;
private submitted: boolean = false;
private active: boolean = true;
constructor(private appService: AppService, private supplierService: SupplierService, private router: Router, private route: ActivatedRoute) {
this.model = new Supplier();
this.route.params.subscribe(params => {
let id = +params['id']; // (+) converts string 'id' to a number
if (!isNaN(id))
this.supplierService.getSupplierById(id)
.subscribe(supplier => this.model = supplier, error => this.errorMessage = error);
});
}
ngOnInit() {
this.getCountries();
}
private getCountries() {
this.appService.getCountry()
.subscribe(countries => this.countries = countries.items,
error => this.errorMessage = error);
}
private navigateToHomePage(supplier) {
if (supplier) {
let link = [''];
this.router.navigate(link);
}
}
private onSubmit(): void {
this.submitted = true;
this.supplierService.saveSupplier(this.model).subscribe(
supplier => this.navigateToHomePage(supplier),
error => this.errorMessage = error);
}
}
very simple component all its doing is getting countries from a service which is using Http call and calling save method on another service which is also http call. I am mocking those services with my Mock classes. below is my test code.
import { By } from '#angular/platform-browser';
import { DebugElement, provide } from '#angular/core';
import { disableDeprecatedForms, provideForms } from '#angular/forms';
import { Router, ActivatedRoute } from '#angular/router';
import * as Rx from 'rxjs/Rx';
import {
beforeEach, beforeEachProviders,
describe, xdescribe,
expect, it, xit,
async, inject, addProviders,
TestComponentBuilder, ComponentFixture
} from '#angular/core/testing';
import { SupplierFormComponent } from './supplier-form.component';
import { SupplierService } from './supplier.service';
import { AppService } from '../shared/app.service';
describe('Component: Supplier', () => {
var builder;
beforeEachProviders(() => {
return [
disableDeprecatedForms(),
provideForms(),
Router, ActivatedRoute,
provide(AppService, { useClass: MockAppService }),
provide(SupplierService, { useClass: MockSupplierService })
];
});
beforeEach(inject([TestComponentBuilder], (tcb) => {
builder = tcb;
}));
it('should create Supplier Component', async(() => {
/*.overrideProviders(
SupplierFormComponent,
[{ provide: AppService, useClass: MockAppService }]
)*/
builder.createAsync(SupplierFormComponent)
.then((fixture: ComponentFixture<SupplierFormComponent>) => {
fixture.detectChanges
var compiled = fixture.debugElement.nativeElement;
console.log(compiled);
})
.catch((error) => {
console.log("error occured: " + error);
});
}));
});
class MockAppService {
public name = "Injected App Service";
public fakeResponse: any = [{ "id": 1, "name": "uk" }];
public getCountry() {
return this.fakeResponse;
}
}
class MockSupplierService {
public name = "Injected Supplier Service";
saveSupplier(supplier: any): boolean {
return true;
}
}
any idea how can i mock router properly with RC.4.