You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
<div*ngIf="condition; else elseBlock">Content to render when condition is true.</div><ng-template#elseBlock>Content to render when condition is false.</ng-template>
@Component({selector: 'app-product-form',templateUrl: './product-form.component.html',styleUrls: ['./product-form.component.css']})exportclassProductFormComponentimplementsOnInit{constructor(privatefb: FormBuilder){}productForm: FormGroup;ngOnInit(){/* Initiate the form structure */this.productForm=this.fb.group({title: [],selling_points: this.fb.array([this.fb.group({point:''})])})}getsellingPoints(){returnthis.productForm.get('selling_points')asFormArray;}/////// This is new /////////////////addSellingPoint(){this.sellingPoints.push(this.fb.group({point:''}));}deleteSellingPoint(index){this.sellingPoints.removeAt(index);}//////////// End ////////////////////}
// import in app.module.ts// import { HttpClientModule } from '@angular/common/http';// imports:[// ....// HttpClientModule// ]// Make request inside a search.service.ts// import { HttpClient } from '@angular/common/http';//addadd(software:Software){returnthis.http.post<Software>(`${this.BASE_URL}/softwares/`,software);}//searchsearch(params:any){returnthis.http.get<any>(`${this.BASE_URL}/softwares/`,{params:params})}
// counter.service.tsinterfaceCount{value: number;}
@Injectable()exportclassCounterService{constructor(){}privateinitialCount: Count={value: 0};privatecountTracker=newBehaviorSubject<Count>(this.initialCount);/** Allows subscription to the behavior subject as an observable */getCount(): Observable<Count>{returnthis.countTracker.asObservable();}/** * Allows updating the current value of the behavior subject * @param val a number representing the current value * @param delta a number representing the positive or negative change in current value */setCount(val: number,delta: number): void{this.countTracker.next({value: (val+delta)});}/** Resets the count to the initial value */resetCount(): void{this.countTracker.next(this.initialCount);}}//counter.component.tsexportclassCounterComponentimplementsOnInit,OnDestroy{constructor(privatecounter: CounterService){}currentCount: number;subscription;ngOnInit(): void{this.subscription=this.counter.getCount().subscribe(res=>{this.currentCount=res.value;},err=>{console.error(`An error occurred: ${err.message}`);});}increment(): void{this.counter.setCount(this.currentCount,1);}decrement(): void{this.counter.setCount(this.currentCount,-1);}reset(): void{this.counter.resetCount();}ngOnDestroy(): void{this.subscription.unsubscribe();}}
AddFilesToFormData(event: any, fileName: string) {
if (event.target.files && event.target.files.length) {
for (const file of event.target.files) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const img = new Image();
img.src = reader.result as string;
img.onload = () => {
const height = img.naturalHeight;
const width = img.naturalWidth;
console.log('Width and Height', width, height);
};
};
}
}
}
Image preview
Image upload & preview
// file.service.ts
import { Injectable } from '@angular/core';
import {HttpClient} from "@angular/common/http";
import {Observable} from "rxjs";
@Injectable({
providedIn: 'root'
})
export class FileService {
BASE_URL = 'http://localhost:8080/api/v1';
constructor(private http: HttpClient) { }
upload(data):Observable<any>{
return this.http.post<any>(`${this.BASE_URL}/files`, data);
}
multiUpload(data):Observable<any>{
return this.http.post<any>(`${this.BASE_URL}/files/multi-upload`, data);
}
}
// add.component.ts
url:any;
constructor(private fileService:FileService) { }
onFileChange(event) {
if (event.target.files.length > 0) {
this.fileName = event.target.files[0];
let reader = new FileReader();
reader.readAsDataURL(event.target.files[0]); // read file as data url
reader.onload = (event) => { // called once readAsDataURL is completed
this.url = reader.result;
}
}
}
onSubmit(form:FormGroup){
const formData = new FormData();
formData.append('file', this.fileName);
this.fileService.upload(formData).subscribe(
data=> {
form.value['image'] = data['url'];
form.value['userId'] = this.auth.currentUserId();
this.portfolioService.save(form.value)
.subscribe(data => {
console.log(data);
this.router.navigate(['/dashboard'])
}, err => console.log(err))
},
error => console.log(error)
)
}
// add.component.html
// <img *ngIf="url" [src]="url" height="200"> <br/>
Tdd
// pipedescribe('TroncaturePipe',()=>{it('create an instance',()=>{constpipe=newTroncaturePipe();// * pipe instantiationexpect(pipe).toBeTruthy();});it('truncate a string if its too long (>20)',()=>{// * arrangeconstpipe=newTroncaturePipe();// * actconstret=pipe.transform('123456789123456789456666123');// * asserexpect(ret.length).toBe(20);});});//// shared/post.service.tsimport{Injectable}from'@angular/core';import{Observable}from'rxjs';import{HttpClient}from'@angular/common/http';exportinterfacePost{userId: number;id: number;title: string;body: string;}
@Injectable({providedIn: 'root'})exportclassPostService{REST_API: string='https://jsonplaceholder.typicode.com/posts';constructor(privatehttp: HttpClient){}getPosts(): Observable<Post[]>{returnthis.http.get<Post[]>(`${this.REST_API}`)}}//import{TestBed,async,inject}from'@angular/core/testing';import{HttpClientTestingModule,HttpTestingController}from'@angular/common/http/testing';import{PostService}from'./post.service';describe('PostService',()=>{letpostService: PostService;lethttpMock: HttpTestingController;beforeEach(()=>{TestBed.configureTestingModule({imports: [HttpClientTestingModule,],providers: [PostService],});postService=TestBed.get(PostService);httpMock=TestBed.get(HttpTestingController);});it(`should fetch posts as an Observable`,async(inject([HttpTestingController,PostService],(httpClient: HttpTestingController,postService: PostService)=>{constpostItem=[{"userId": 1,"id": 1,"title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit","body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"},{"userId": 1,"id": 2,"title": "qui est esse","body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"},{"userId": 1,"id": 3,"title": "ea molestias quasi exercitationem repellat qui ipsa sit aut","body": "et iusto sed quo iure\nvoluptatem occaecati omnis eligendi aut ad\nvoluptatem doloribus vel accusantium quis pariatur\nmolestiae porro eius odio et labore et velit aut"}];postService.getPosts().subscribe((posts: any)=>{expect(posts.length).toBe(3);});letreq=httpMock.expectOne('https://jsonplaceholder.typicode.com/posts');expect(req.request.method).toBe("GET");req.flush(postItem);httpMock.verify();})));});``