我最近了解到,我们必须在 Angular 销毁组件之前取消订阅,否则可能会导致内存泄漏。
我还知道我们可以获得订阅的引用,并通过调用该订阅的取消订阅方法来订阅。例如
private sub: any;
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = +params['id']; // (+) converts string 'id' to a number
this.service.getHero(id).then(hero => this.hero = hero);
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
Run Code Online (Sandbox Code Playgroud)
在 HTTP 调用的情况下也有必要吗?如果是,那么这种情况下的最佳实践是什么。
例如,我们通常有这样的东西通过 HTTP 发布一些数据
let body = JSON.stringify({ name });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post(this.heroesUrl, body, options)
.map(this.extractData)
.subscribe((data) => {
//do something with data
})
.catch(this.handleError);
Run Code Online (Sandbox Code Playgroud)
下面的方法可行吗?这是在 HTTP …
我有一个服务(AuthService),我需要在我的restangularInit函数(在我的 app.module.ts 中)中访问它,但我不知道如何访问它,我无法访问它。
我试图将它移动到 AppModule 类中,但到那时它\xc2\xb4s 已经晚了。
\n\n调用服务功能,例如。getToken按预期工作。
import { BrowserModule } from \'@angular/platform-browser\';\nimport { NgModule } from \'@angular/core\';\nimport { FormsModule } from \'@angular/forms\';\nimport { HttpModule } from \'@angular/http\';\nimport { MaterialModule } from \'@angular/material\';\nimport { FlexLayoutModule } from "@angular/flex-layout";\nimport { RestangularModule } from \'ng2-restangular\';\n\n// Components\nimport { AppComponent } from \'./app.component\';\nimport { ProductComponent } from \'./components/product/product.component\';\n\n// Services\nimport { AuthService } from \'./services/auth.service\';\n\nexport function restangularInit(RestangularProvider, AuthService) {\n console.log(AuthService); // this is undefined\n let token = …Run Code Online (Sandbox Code Playgroud) 我的应用程序中的一项服务存在问题。问题是,无论在何处注入此服务,我都会收到以下错误:
Uncaught (in promise): Error: Can't resolve all parameters for TestComponent: ([object Object], ?, [object Object])
Run Code Online (Sandbox Code Playgroud)
我知道这个问题可能是由于使用桶引起的,但是我没有将桶用于服务,而是“直接”引用文件,例如:../../core/services/config.service。
正如这个答案@Inject(forwardRef(...))中所建议的,我尝试在注入该服务的任何地方使用。我唯一的例外是AppComponent在这种情况下我“正常”注入相同的服务并且没有收到错误:
export class AppComponent implements OnInit {
constructor(
private configService: ConfigService, // NO ERROR
private router: Router
) { }
...
}
Run Code Online (Sandbox Code Playgroud)
在所有其他地方,如果我不执行以下操作,我会收到上述错误:
export class BuyButtonComponent {
constructor(
@Inject(forwardRef(() => ConfigService)) private configService: ConfigService,
// private configService: ConfigService // DOES NOT WORK
) { }
...
}
Run Code Online (Sandbox Code Playgroud)
据我了解,forwardRef()当要注入依赖项但尚未定义时使用。是ConfigService从CoreModule中导入的提供的AppModule。这些组件位于我拥有的a …
我这里有组件代码,当我订阅可观察对象时,服务被调用两次,但是如果我订阅Behavioursubject,它只会触发一次,
我可以在我的日志中看到这些结果,请参阅下面我的组件代码,在 ngOninit 上调用 subscribeToMap() 方法。
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import { HeroSearchService } from './hero-search-service';
import { Hero } from './../hero';
@Component({
selector: 'hero-search',
templateUrl: './hero-search.component.html',
styleUrls: [ './hero-search.component.css' ],
providers: [HeroSearchService]
})
export class HeroSearchComponent implements OnInit {
heroes: Observable<Hero[]>;
private searchTerms …Run Code Online (Sandbox Code Playgroud) 这是在 Angular 2 中下载 pdf 文件的功能,当我下载 Pdf 文件时,它是损坏的文件。那么我该如何解决这个问题。\n它显示的是这样的损坏数据。\n%PDF-1.5\n%\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd \n\xe2\x86\xb566 0 对象\n<>\nendobj
\n\ndownloadFile() {\n //this.http.get('https://contactsapi.apispark.net/v1/companies/').subscribe(\n this.http.get('assets/Files/booking.pdf').subscribe(\n (response: any) => {\n console.log(response);\n let parsedResponse =(response)\n var blob = new Blob([response], {type: 'application/pdf'});\n var filename = 'booking.pdf';\n saveAs(blob, filename);\n });\n }\nRun Code Online (Sandbox Code Playgroud)\n 我正在创建一个服务来检查用户是否登录。这只是一个从后端传递的全局变量“userIsLoggedIn”。该服务将在多个应用程序中使用,有时 userIsLoggedIn 全局变量将不存在。
我所拥有的是...
import { Injectable } from '@angular/core';
declare const userIsLoggedIn: boolean;
@Injectable()
export class UserLoggedInService{
isUserLoggedIn(): boolean {
return userIsLoggedIn || false;
}
}
Run Code Online (Sandbox Code Playgroud)
如果 userIsLoggedIn 全局变量不存在,则会收到错误,如果省略声明行,则会收到错误。
我曾希望能够做类似的事情
declare const userIsLoggedIn?: boolean;
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用。有人可以帮我吗?
我有一个呈现房地产属性的组件 (properties.component.html)。当用户单击特定属性时,我设置了一个等于该属性的行为主题。
private property = new BehaviorSubject<Property>();
setProperty(property) {
this.property.next(property);
}
Run Code Online (Sandbox Code Playgroud)
组件 (property.component.html) 可以很好地呈现从 Behavior Subject 服务中的 observable 返回的数据。
this.propertyService.getProperty()
.subscribe((property) => {
this.currentProperty = property;
})
Run Code Online (Sandbox Code Playgroud)
我的问题:当页面重新加载时,行为主题现在是“空的?” 没有数据,因为单击时会在 properties.component.html 中调用 .next(property)。
应用程序如何在页面刷新/重新加载时保存数据?
另一张海报提到将属性作为字符串化 JSON 存储在 localStorage 中。如果这是解决方案,那么用户如何通过直接访问https://www.myapp.com/property/1234 来访问此特定属性?
我的 Angular 2 项目中有一个函数
this.fetchedData= this._visitService.getchartData().toPromise();
console.log("WORKING I HOPE0", this.fetchedData)`
Run Code Online (Sandbox Code Playgroud)
给出输出:
WORKING I HOPE0
ZoneAwarePromise {__zone_symbol__state: null, __zone_symbol__value: Array(0)}
__zone_symbol__state:true
__zone_symbol__value:Array(2)
0:{date: "2018, 03, 14", value: 11}
1:{date: "2018, 03, 15", value: 1}
length:2
__proto__:Array(0)
__proto__:Object`
Run Code Online (Sandbox Code Playgroud)
是否可以__zone_symbol__value将其整体作为对象进行访问,甚至只是从中检索数据。我尝试使用console.log("WORKING I HOPE0", this.fetchedData.__zone_symbol__value)但似乎不起作用。我并不是在寻找任何替代方法。所以如果我想知道它是否可能以及为什么或为什么不可行。
我在 angular5 简单项目(前端)和后端(弹簧引导)中工作,我想向带有 2 个参数 idPerson 和 idProject 的 api rest 发送 post 请求,因此 api rest 可以影响项目到选定的人,我尝试在带有 POST 的服务中执行此操作,但这是不可能的。
这是 ProjectService.ts 的代码
addProjToClient(idPerson:number,idProject:number){
if(this.authService.getToken()==null) {
this.authService.loadToken();
}
return this.http.post(this.host+"/saveProjectToClient",idPerson,idProject,{headers:new HttpHeaders({'Authorization':this.authService.getToken()})});
}
Run Code Online (Sandbox Code Playgroud)
不可能在 http Post 中发送超过 2 个参数,我使用 httpClient 。
关于如何做到这一点的任何想法?
我是Typescript和javascript的新手.我的问题是:怎么做到这一点
```
{
"release": {
"ref": {},
"commits": {}
},
"debug": {
"ref": {},
"commits": {}
},
"feature": {
"ref": {},
"commits": {}
},
"hotfix": {
"ref": {},
"commits": {}
}
}
Run Code Online (Sandbox Code Playgroud)
```
使用接口使用Typescript映射它
export interface IRepo {
branches: IBranch; // how to make branches a of type string: IBranch dictionary?
}
将有未知数量的属性,如调试,发布等,我想在IRepo实例中将它们保留为字典
我正在使用它来获取数据:
```
getRepo() : Observable<IRepo> {
if (!this.repo) {
return this.http.get(this._baseUrl + 'repo.json')
.map((res: Response) => {
this.repo = res.json();
return this.repo;
})
.catch(this.handleError);
} else { …Run Code Online (Sandbox Code Playgroud) angular ×8
typescript ×2
angular5 ×1
dictionary ×1
httpclient ×1
javascript ×1
json ×1
object ×1
restangular ×1
rxjs ×1